【问题标题】:Why is my redux state not updating after dispatch [closed]为什么我的redux状态在调度后没有更新[关闭]
【发布时间】:2021-09-02 01:45:25
【问题描述】:

我正在使用 redux-thunk 进行反应,当我调度操作以调用 api 时,我可以在 redux 开发工具中看到数据更新,但它没有在组件上呈现。

我的行动:

 export const fetchPosts = () => async(dispatch) => {
try {
    const {data} = await API.fetchPosts();
    dispatch({
        type: "FETCH_POSTS",
        payload: {
            posts: data.posts
        },
      });

  } catch (error) {
    console.log(error)
  }
  }

减速机:

const postsReducers = (state = [], action) => {
switch (action.type) {
case "FETCH_POSTS":
    state.push(...action.payload.posts);
  return state;

default:
  return state;
 }
};

export default postsReducers;

组件:

const Home = () => {
const dispatch = useDispatch();
const posts = useSelector(state => state.posts);

useEffect(() => {
  if(!posts.length){
    dispatch(fetchPosts())
     console.log(posts.length) //returns 0
  }
}, [dispatch, posts]);

....
}

我可能会错过什么?

【问题讨论】:

  • 你应该总是在 reducer 中返回一个新的状态 --> return {...state}
  • 你的状态数据结构是什么?
  • 感谢大家的帮助,我得到了答案

标签: reactjs redux redux-thunk


【解决方案1】:

除非您使用新的 redux 工具包,否则 redux 要求您不要改变状态。

尝试使用扩展运算符创建一个新数组,而不是推送到状态并返回一个变异状态:

return [...state, ...action.payload.posts];

【讨论】:

    猜你喜欢
    • 2017-01-25
    • 1970-01-01
    • 2020-04-14
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    相关资源
    最近更新 更多