我有一个动作调度员从博客文章中获取评论,直接从API
服务器然后发送动作。
export function fetchPostComments(postID) {
return (dispatch) => {
fetch(`${url}/posts/${postID}/comments`, { method: 'GET', headers})
.then((response) => response.json())
.then((comments) => {console.log("action ", comments); dispatch(getPostComments(comments))})
.catch((error)=>{console.log('fetch comments error',error)});
};}
如上所示我是console.log
it,它给出了我正在寻找的结果,如下所示。
以下是我发布动作的方式。
export function getPostComments (comments) {
return {
type: GET_POST_COMMENTS,
comments
}
}
现在这是我的减速机:
function comments (state = {}, action) {
switch (action.type) {
case GET_POST_COMMENTS:
console.log("Reducer comments ", action.comments);
return action.comments;
default :
return state
}
}
如果你再次观察,我使用console.log
来确认结果,并再次得到我想要的正确结果,如下所示:
现在,在我的一个组件中,我显示博客帖子信息和查看评论的链接。用户单击视图注释后,将触发调用操作调度程序。
<div className="row">
<a onClick={this.handleFetchComments} href=""><span className="float-date"><strong style={{fontWeight:'bold'}}>View Comments</strong></span></a>
</div>
<div>
<div>
<span>Count : { this.state.comments.length }</span>
</div>
<textarea placeholder="Add your comments here"></textarea>
<input type="submit" value="+Add comment" />
</div>
这是获取注释的处理程序:
handleFetchComments = (e) => {
e.preventDefault();
const comments = this.props.getAllComments(this.props.postID);
console.log("Comments fetch ", comments);
setInterval(this.loadComments(comments),1000);
}
loadComments(comm) {
console.log("Before ", this.state.comments);
this.setState(()=>({comments:comm}));
console.log("After ", this.state.comments);
}
我把一些console.log
只是为了检查结果,这是我得到的结果,这是错误的,并且刚刚与reducer产生的结果不兼容。它给出了一个来自调度操作的未定义和空结果,如下面的结果所示:
同时,每当我点击View Comments链接时,我的Redux
Dev工具,它会显示我想要的正确数据并触发调度操作,如下所示。
这是我在Component
上的状态,它有查看评论的链接:
state = {
post: [],
hasClickComments : false,
comments: []
}
这是我的mapStateToProps
中的App.js
:
function mapStateToProps ({posts, comments, categories}) {
return {
posts: posts,
comments: comments,
categories: categories,
}
}
这是我的mapDispatchToProps
:
function mapDispatchToProps (dispatch) {
return {
getAllComments: (postID) => dispatch(fetchPostComments(postID)),
}
}
我还有其他行动,我发送mapDispatchtoProps
,到目前为止,除了这一个,它都是有效的。
我是React
和Redux
的新手,我正在寻找这个近两天的解决方案,但无法弄明白。什么可能出错?
你混合使用React Component的State和props.State And Props
在mapStateToProps
之后,所有数据都成为组件的道具。
你应该使用this.props.comments
来获取你的数据!
function comments (state = {}, action) {
switch (action.type) {
case GET_POST_COMMENTS:
console.log("Reducer comments ", action.comments);
return {
...state,
comments: action.comments;
}
default :
return state
}
}
如果你的评论数据在redux中,那么问题就在于你使用mapStateToProps的方式。我建议你在函数中使用调试器并找到你所处的状态。
function mapStateToProps (state) {
debugger
//return {
// posts: posts,
// comments: comments,
// categories: categories,
//}
}
现在查看控制台上的状态数据。然后将数据分配给所需的变量。