Redux状态没有立即更新? [英] Redux state not updating right away?
本文介绍了Redux状态没有立即更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
setCurrentPage只是将对象存储到我的全局存储中的一个页面对象中。因此,如果我在设置后立即尝试访问它..好像有延迟,物体是空的。但如果我在之后将相同的对象统一记录在一个按钮中并单击它..已填充。
有没有我不知道的复印滞后?我能做些什么才能让它起作用呢?它弄乱了我的代码..。
感谢您的帮助
// initialState.js // my global redux store
playlist: {
currentPage: {}
}
// someComponent
let tempPage = new Page();
tempPage.controlNode = someAPItoGetControlNode(); //synchronous
this.props.actions.setCurrentPage(tempPage); //tempPage.controlNode contains object correctly
console.log(this.props.currentPage); //empty object. WHY???
// in some function in the same component i call in a button
function seeCurrentPage() {
console.log(this.props.currentPage); //works!
}
// reducer
case types.SET_CURRENT_PAGE: {
action.pageObj.selected = true;
return Object.assign({}, state, {currentPage: action.pageObj});
}
// action
export function setCurrentPage(pageObj) {
return { type: types.SET_CURRENT_PAGE, pageObj: pageObj };
}
推荐答案
信息延迟的原因不是因为还原,而是因为component
的异步执行。
// someComponent
let tempPage = new Page();
tempPage.controlNode = someAPItoGetControlNode(); //synchronous
this.props.actions.setCurrentPage(tempPage); //tempPage.controlNode contains object correctly
console.log(this.props.currentPage);
在上面的代码中,组件触发一个操作,然后紧跟在日志this.props.currentPage
之后。但是,到那个时候,Redux存储还没有更新,因此您会得到一个较旧的结果
您可以做的是登录componentWillReceiveProps
函数,如
componentWillReceiveProps(nextProps) {
console.log(nextProps.currentPage)
}
这篇关于Redux状态没有立即更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文