繁体   English   中英

在 redux 中使用来自 state 的返回数据时出现错误

[英]I have an error when using returning data from state in redux

当我尝试更新任何帖子时,它会在数组中返回一个数组,如下所示

((3) [{…}, 数组(3), 数组(3)])

这是第一个帖子和两次相同的数组,所以当我在更新一个帖子后渲染帖子时,只显示更新后的帖子

这是调度动作的代码

export const updatePost =(id, post) => async (dispatch) => {
try {
    const {data}  = await api.updatePost(id, post)
    dispatch({type:'UPDATE',payload:data})
    // console.log(data)

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

}

这就是行动

export default (posts=[],action) =>{
switch (action.type) {
    case 'FETCH_ALL':
        return action.payload
    case 'CREATE':
        return [...posts, action.payload]
    case 'LikePost':
    case 'UPDATE':
            // return [...posts, action.payload]
          return  posts.map(post => post._id===action.payload._id ? action.payload : posts)
    case 'DELETE':
        return posts.filter((post)=> post._id!==action.payload)
  

    default:
        return posts
} }

这是减速机

import { combineReducers } from "redux";
import posts from './Posts'
export default  combineReducers({posts})

这是我从 redux state 获取数据的方法

 import { Grid, CircularProgress } from '@material-ui/core';
 import { useSelector } from 'react-redux';

 import Post from './Post/Post';
 import useStyles from './Styles';

const Posts = ({ setCurrentId }) => {
const posts = useSelector((state) => state.posts);
const classes = useStyles();

return (
 !posts.length ? <CircularProgress /> : (
   <Grid className={classes.container} container alignItems="stretch" spacing={3}>
     {posts.map((post) => (
       <Grid key={post._id} item xs={12} sm={6} md={6}>
         <Post post={post} setCurrentId={setCurrentId} />
       </Grid>
     ))}
   </Grid>
 )
);
};

export default Posts;


问题出在你的行动上; 您正在这一行中自己创建这个嵌套数组:

return posts.map(post => {
  post._id === action.payload._id ? // if this is the post
    action.payload :                // use updated data
    posts                           // --error--: copy entire posts array
})

因此,对于每个未更新帖子的元素,您将用整个帖子数组替换它。 如果您想使用此模式,只需将posts替换为post

return posts.map(post => post._id === action.payload._id ? action.payload : post)

问题未解决?试试以下方法:

在 redux 中使用来自 state 的返回数据时出现错误

暂无
暂无

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

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