Javascript 动作分派后无法获得新道具
我有一个反应组件:Javascript 动作分派后无法获得新道具,javascript,reactjs,ecmascript-6,redux,Javascript,Reactjs,Ecmascript 6,Redux,我有一个反应组件: 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
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();
}
}
//...
}
我的问题是:为什么我的compareLastPair函数得到了与在handleClick函数中分派之前相同的道具,尽管状态是由Redux更新的(您可以在图中的Redux logger中看到),并且ClickedTitles数组应该由reducer连接。即使分派操作是同步的(但我们不知道……您没有共享代码),React组件中的道具更新遵循正常的异步生命周期,同时在分派后显式调用
CompareAlstPair
React/Redux不以这种方式工作:您的组件将在您的呼叫后收到新的道具
对于您的测试,我建议您在
componentDidUpdate
生命周期方法中调用compareLastPair
,该方法在道具更改后调用。即使您的调度操作是同步的(但我们不知道……您没有共享代码),React组件中的道具更新遵循正常的异步生命周期,同时在分派后显式调用CompareAlstPair
React/Redux不以这种方式工作:您的组件将在您的呼叫后收到新的道具
对于您的测试,我建议您在
componentdiddupdate
生命周期方法中调用compareLastPair
,该方法在道具更改后调用。我将在componentWillReceiveProps
或getDerivedStateFromProps
生命周期方法中调用compareLastPair
方法(取决于或反应版本。在最新反应版本中,组件WillReceiveProps
已弃用,并将在版本17中删除).componentWillReceiveProps
在装入的组件接收新道具之前被调用,而getDerivedStateFromProps
在调用render方法之前被调用。我将在componentWillReceiveProps
或getDerivedStateFromProps
生命周期方法中调用compareLastPair
方法(取决于或反应版本。在最新的反应版本中,componentWillReceiveProps
已弃用,并将在版本17中删除)。componentWillReceiveProps
在装入的组件接收新的props之前被调用,并且在调用呈现方法之前被调用。
const gameplay = (state = {board: [], clickedTiles: [], pairedTiles: [], round: 0}, action) => {
switch(action.type) {
case 'CLICK_TILE':
return {...state, ...{clickedTiles: state.clickedTiles.concat(action.id)}}
}
}