react-redux 中的 CRUD,显示来自其他页面的帖子详细信息



我是 react-redux 的新手,我认为状态管理有问题。我想从主页的主表中获取帖子详细信息,以便在详细信息页面中显示帖子详细信息...当我单击按钮详细信息时,我更改了路径"/details/1,并且我想显示id=1的帖子。我得到{post: undefined, getDetails: ƒ}

操作.js

export const postDetails = (data, id) => ({
type: "POST_DETAILS",
post: data,
id: id
})

减速器.js

case "POST_DETAILS":
return state.posts.map((post) => {
if(post.id === action.id) {
return {
...post,
post: post
}
} 
})

容器 - 获取详细信息.js

const mapStateToProps = state => ({ post: state.post });
const mapDispatchToProps = dispatch => {
return {
getDetails: (data, id) => dispatch(postDetails(data, id))
};
};

const GetDetails = connect(
mapStateToProps,
mapDispatchToProps
)(Details)

export default GetDetails;

组件详细信息.js

class Details extends React.Component {
constructor(props){
super(props);
}
componentDidMount() {
this.props.getDetails(this.props.post, this.props.id);
}
render() {
return (
<div>
Details page
<ul>
<li>
{this.props.post}
</li>
</ul>
</div>
)
}
}
export default Details;

您的化简器正在破坏自己的状态,直到状态变得未定义。您从一个作为对象的状态开始,但您只返回该对象的一个字段。

从这样的状态开始:

{
loading: false,
posts: [
{
id: 1
post: 'foo',
author: 'bar'
},
{
id: 2
post: 'fooz',
author: 'barz'
}
]
}

调度如下操作:

{
type: "POST_DETAILS",
id: 1,
post: 'this is never accessed'
}

将生成一个数组

[
{
id: 1
post: {
id: 1
post: 'foo',
author: 'bar'
},
author: 'bar'
},
undefined
]

再次调度操作将导致状态undefined

第三次将导致错误。

在你的减速器中,你可能打算做这样的事情。

case "POST_DETAILS":
return { ...state, posts: state.posts.map((post) => {
if(post.id === action.id) {
return {
...post,
post: action.post
}
} else {
return post
}
})
}

相关内容

最新更新