简体   繁体   English

无法正确处理 state“加载”与 redux 反应

[英]Unable to handle state 'loading' properly in react with redux

Hey guys just moved to redux so in react what i was doing was in componentDidMount(), i was calling api and soon as i received the data i was setting loading to false (initially loading was true) to get rid of the 'react spinner',嘿,伙计们刚刚搬到 redux,所以我正在做的反应是在 componentDidMount() 中,我打电话给 api,一旦我收到数据,我就将加载设置为 false(最初加载为 true)以摆脱“反应微调器” ',

but after using redux now in componentDidMount() i am calling my action creater which is in another and there i am receving my data so how do i manage 'loading' here?但是现在在 componentDidMount() 中使用 redux 之后,我正在调用另一个在另一个中的操作创建器,并且我正在接收我的数据,那么我如何在这里管理“加载”? can i somehow pass something from action creater to my component that triggers state and set loading to false?我可以以某种方式将动作创建器中的某些内容传递给我的组件,以触发 state 并将加载设置为 false? or is there any other to do it?或者还有其他方法吗? How do you all manage it?大家都是怎么管理的?

here is my code这是我的代码

Home.js主页.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);

and my action.js file和我的 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));
  };
};

reducer file减速器文件

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

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

};

export default getCategoryReducer;

You should handle the loading state in your reducer file.您应该在reducer文件中处理加载 state。 At the moment, it's defined in your Component file.目前,它在您的Component文件中定义。 For eg when you dispatch the action, it should update your loading state too.例如,当您调度操作时,它也应该更新您的加载 state。 I would do something like this in reducer.我会在减速器中做这样的事情。

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;

and your action file would look something like this你的动作文件看起来像这样

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 }););
  };
};

You can then read the loading props in your Home.js然后,您可以在Home.js中阅读加载道具

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM