Redux 状态没有立即更新?

Redux state not updating right away?

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 };
}

更新 Redux store 后,您的组件将需要重新渲染。

所以你可以在componentWillReceiveProps(nextProps)componentDidUpdate()中写入console.log,然后你就可以从商店访问新数据。

延迟信息的原因不是因为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);  

在上面的代码中,您的组件触发一个动作,然后在记录 this.props.currentPage 之后立即触发。然而到那个时候 redux store 不会更新,因此你得到一个旧的结果

您可以像

一样登录componentWillReceiveProps功能
componentWillReceiveProps(nextProps) {
     console.log(nextProps.currentPage)
}

我刚刚运行也入了这个。像大家说的更新道具时,这是一个异步问题。我通过使用异步等待解决了它。如果你想立即获得更新的道具,那么你可以这样做:


    async function myFunction () {
      await this.props.actions.setCurrentPage(tempPage);
      console.log(this.props.currentPage); // shows updated props
    }

在此代码中,控制台日志等待异步操作完成,然后获取您的道具。