Redux 状态没有立即更新?

use*_*352 4 reactjs redux react-redux

setCurrentPage 只是将对象存储到我的全局存储中的页面对象中。所以如果我在设置后尝试立即访问它..似乎有延迟并且对象是空的。但是如果我在按钮中console.log相同的对象并单击它..它就会被填充。

redux 是否存在我不知道的延迟?我该怎么做才能让它发挥作用?它弄乱了我的代码......

谢谢你的帮助

// 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 };
}
Run Code Online (Sandbox Code Playgroud)

Shu*_*tri 5

延迟信息的原因不是因为 redux,而是因为您的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);  
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,您的组件触发一个操作,然后立即触发 log this.props.currentPage。然而到那时,redux 存储还没有更新,因此你会得到一个较旧的结果

您可以做的就是登录该componentWillReceiveProps功能,例如

componentWillReceiveProps(nextProps) {
     console.log(nextProps.currentPage)
}
Run Code Online (Sandbox Code Playgroud)