简体   繁体   English

行动派遣后无法获得新道具

[英]Can not get new props after action dispatching

I have a React component: 我有一个React组件:

class Board extends React.Component { 
  // ...
  compareLastPair() {
    const {gameplay} = this.props;
    console.log('after dispatching, before compare', gameplay.clickedTiles); //-> [1] 

    // i got old state as before dispatching an action, but expected refreshed props
    // thus, condition below never executes 

    if(gameplay.board.length === gameplay.pairedTiles.length + gameplay.clickedTiles.length) {
      this.compareTiles();
    }
  }

  handleClick(id) {
    const {gameplay, dispatch} = this.props;
    // ...some code
    else if(!gameplay.clickedTiles.includes(id) && gameplay.clickedTiles.length < 2) {
      console.log('before dispatching', gameplay.clickedTiles); // -> [1]          
      dispatch(clickTile(id));
      this.compareLastPair();           
    }
  }
  //...
}

My reducer dispatches sync action: 我的减速器调度同步操作:

 const gameplay = (state = {board: [], clickedTiles: [], pairedTiles: [], round: 0}, action) => {
      switch(action.type) {
        case 'CLICK_TILE':
          return {...state, ...{clickedTiles: state.clickedTiles.concat(action.id)}} 
       }
    }

我的日志

My question is: why my compareLastPair function gets the same props as before dispatching in handleClick function, despite the fact that the state was updated by Redux(you can see it in Redux-logger at the image) and clickedTiles array should be concantenated by reducer. 我的问题是:为什么我的compareLastPair函数与handleClick函数中的调度之前获得了相同的道具,尽管事实上状态是由Redux更新的(您可以在Redux-logger中在图像上看到它),而clickedTiles数组应由reducer来强化。

Even if your dispatch action is synchronous (but we don't know... you didn't shared the code), props update in the React component follow the normal asynchronous lifecycle, while you are explicitly calling compareLastPair after the dispatch. 即使您的调度动作是同步的(但我们不知道...您没有共享代码),React组件中的props更新也会遵循正常的异步生命周期,而在调度后您显式调用了compareLastPair

React/Redux do not work this way: new props will be received by your component after your call. React / Redux不能这样工作:调用 ,组件会收到新的道具。

For your test, I suggest you to call compareLastPair inside the componentDidUpdate lifecycle method, which is called after prop changes. 为了进行测试,建议您在componentDidUpdate生命周期方法内调用compareLastPair ,该compareLastPair在更改compareLastPair后调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM