【问题标题】:How to separate redux api calls如何分离 redux api 调用
【发布时间】:2020-04-23 03:53:09
【问题描述】:

我有一个“fetchComments”和“fetchCommentsById”。目前,当我 console.log props.cmets 时,我会记录所有 cmets 并评论 62,有没有办法将两者分开?

const MainPage = (props) => {
  useEffect(() => {
    props.fetchComments();
    props.fetchCommentById(62);
  }, []);

  console.log("all comments: ", props.comments);

  return (
    <>
      <div>MainPage</div>
    </>
  );
};

const mapStateToProps = (state) => {
  return { comments: state.comments };
};

export default connect(mapStateToProps, { fetchComments, fetchCommentById })(
  MainPage
);

这是我的 cmets 减速器。

export default (state = [], action) => {
  switch (action.type) {
    case FETCH_COMMENTS:
      return [...state, action.payload];
    case FETCH_COMMENT_BY_ID:
      return action.payload;
    default:
      return state;
  }
};

【问题讨论】:

    标签: reactjs api redux axios


    【解决方案1】:

    在您的 reducer 中,不要只将 cmets 存储在数组中,而是存储一个同时包含完整 cmets 和 commentById 的对象。

    主页组件:

    const MainPage = (props) => {
      useEffect(() => {
        props.fetchComments();
        props.fetchCommentById(62);
      }, []);
    
      console.log("all comments: ", props.comments);
      console.log("comment by id: ", props.commentById);
    
      return (
        <>
          <div>MainPage</div>
        </>
      );
    };
    
    const mapStateToProps = (state) => {
      return { 
        commentById: state.comments.commentById,
        comments: state.comments.comments
      };
    };
    
    export default connect(mapStateToProps, { fetchComments, fetchCommentById })(
      MainPage
    );
    

    像这样改变你的减速器:

    const initialState = {
      comments: [],
      commentById: ''
    }
    export default (state = initialState, action) => {
      switch (action.type) {
        case FETCH_COMMENTS:
          return {...state, comments: action.payload}; // assuming you are returning an array from the server
        case FETCH_COMMENT_BY_ID:
          return {...state, commentById: action.payload};
        default:
          return state;
      }
    };
    

    【讨论】:

    • 非常感谢,它成功了。我必须在初始状态下将 commentById 更改为等于空字符串,因为当我将其渲染到 DOM 时它会引发错误。
    • 太棒了...我已经用empty string更新了答案...如果有帮助,您可以考虑接受答案...谢谢。
    猜你喜欢
    • 2017-05-25
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2021-11-21
    • 2019-10-01
    • 2019-02-21
    • 1970-01-01
    相关资源
    最近更新 更多