我正在使用 redux-thunk 的 react,当我调度 action 来调用 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]);
....
}
我会遗漏什么?
答案 0 :(得分:0)
除非你使用新的 redux 工具包,否则 redux 要求你不要改变 state。
不要推送到状态并返回变异状态,而是尝试使用扩展运算符创建一个新数组,如下所示:
return [...state, ...action.payload.posts];