Incapaz de manejar 'carga' estado adecuadamente en reaccionar con redux

Ratnabh Kumar Rai:

Hola chicos acabo de mudar a Redux por lo que en reacciono lo que estaba haciendo estaba en componentDidMount (), que estaba llamando la API y nada más recibido los datos que estaba ajustando la carga en false (inicialmente carga era cierto) para deshacerse de la 'reaccionar spinner ',

pero después de usar redux ahora en componentDidMount () Estoy llamando a mi acción creater que está en otra y no estoy Receving mis datos así que ¿cómo puedo administrar 'carga' aquí? ¿Hay algún modo pasar algo de acción creater a mi componente de ese estado de carga y factores desencadenantes conjunto de falsa? o ¿hay algún otro para hacerlo? ¿Cómo se todo lo maneja?

aquí es mi código

Home.js

class home extends Component {
  UNSAFE_componentWillMount() {
    this.props.verifyToken();
  }

  componentDidMount() {
    this.props.categoryAction();

  }
  constructor(props) {
    super(props);
    this.state = {
      categoriesWithTheirImages: [],
      displayToggle: false,
      loading: false,
    };
  }


  renderCategory = () => {

    return this.props.allCategories.map((item) => {
      return (
        <div
          className="category_div"
          key={item._id}
          onClick={() => this.setState({ displayToggle: true })}
        >
          <img
            src={item.image}
            alt="miss-mistake"
            className="category_image_home"
          />
          <span className="category_heading_home">{item.categoryName}</span>
        </div>
      );
    });

  };

  render() {

    if (this.state.loading) {
      return (
        <div className="sweet-loading-main">
          <FadeLoader
            css={override}
            sizeUnit={"px"}
            size={50}
            color={"#ff9d72"}
            loading={this.state.loading}
          />
        </div>
      );
    } else {
      console.log(this.props.allCategories);
      return (
        <React.Fragment>
          {/* <Fade left> */}
          <Header />
          <div className="main_content_homepage">
            <p className="category_select">Please select a category</p>
            <div className="category_list">{this.renderCategory()}</div>
          </div>
          {this.renderStoryActionDialog()}
          {/* </Fade> */}
        </React.Fragment>
      );
    }
  }
}


const mapStateToProps = (state) => {
  console.log(state);
  const images = [family, ring, beer, feedback, academic];
  let categoriesWithImages = state.getCategoryReducer.map((item, index) => {
    item.image = images[index];
    return item;
  });
  console.log(categoriesWithImages);
  return { allCategories: categoriesWithImages };
};
export default connect(mapStateToProps, { verifyToken, categoryAction })(home);

y mi archivo action.js

import { CATEGORY } from "../actionTypes";
export const categoryAction = ()=> {
  return dispatch => {
    fetch("http://localhost:3000/api/get_categories", {
      method: "GET",
    }).then(res=>res.json())
      .then(response => {
          console.log(response)
        dispatch({ type: CATEGORY, payload: response });
      })
      .catch(err => console.log("Eror in adding", err));
  };
};

archivo reductor

import { USER, CATEGORY} from "../actionTypes";
const getCategoryReducer = (state = [], action) => {

  switch (action.type) {
    case CATEGORY:
      return action.payload;
    default:
      return state;
  }

};

export default getCategoryReducer;
Sid:

Usted debe manejar el estado de carga en su reducerarchivo. Por el momento, se define en su Componentarchivo. Por ejemplo, cuando se despacha la acción, debe actualizar su estado de carga también. Me gustaría hacer algo como esto en el reductor.

import { USER, FETCH_CATEGORY, FETCH_CATEGORY_SUCCESS, FETCH_CATEGORY_FAIL} from "../actionTypes";
const INITIAL_STATE = {
    loading: false,
    err: false,
    data: []
}
const getCategoryReducer = (state = INITIAL_STATE, action) => {

  switch (action.type) {
    case FETCH_CATEGORY:
       return Object.assign({}, state, {
            loading: true,
            data: [],
        })

      case FETCH_CATEGORY_SUCCESS
          return Object.assign({}, state, {
            loading: false,
            data: action.payload,
        })

       case FETCH_CATEGORY_FAIL
          return Object.assign({}, state, {
            loading: false,
            data: action.payload,
            err: true
        })

    default:
      return state;
  }

};

export default getCategoryReducer;

y el archivo de acción podría ser algo como esto

import { FETCH_CATEGORY, FETCH_CATEGORY_SUCCESS, FETCH_CATEGORY_FAIL } from "../actionTypes";
export const categoryAction = ()=> {
  //setting loading to true
  return dispatch => {
    dispatch({ type: FETCH_CATEGORY });
    fetch("http://localhost:3000/api/get_categories", {
      method: "GET",
    }).then(res=>res.json())
      .then(response => {
         //setting loading to false
        dispatch({ type: FETCH_CATEGORY_SUCCESS, payload: response });
      })
      .catch(err => console.log("Eror in adding", err);  dispatch({ type: FETCH_CATEGORY_FAIL, payload: err }););
  };
};

A continuación, puede leer los puntales de carga en su Home.js

Supongo que te gusta

Origin http://10.200.1.11:23101/article/api/json?id=406914&siteId=1
Recomendado
Clasificación