Redux状态没有立即更新?

人气:977 发布:2022-10-16 标签: reactjs redux react-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)
}

538