我有一个 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();
}
}
//...
}
我的 reducer 调度同步操作:
const gameplay = (state = {board: [], clickedTiles: [], pairedTiles: [], round: 0}, action) => {
switch(action.type) {
case 'CLICK_TILE':
return {...state, ...{clickedTiles: state.clickedTiles.concat(action.id)}}
}
}
我的问题是:为什么我的compareLastPair函数获得与在handleClick函数中调度之前相同的 Prop ,尽管事实上状态是由Redux更新的(您可以在图像中的Redux-logger中看到它)并且clickedTiles数组应该是由reducer连接起来。
最佳答案
即使您的调度操作是同步的(但我们不知道...您没有共享代码),React 组件中的 props 更新也会遵循正常的异步生命周期,而您显式调用 compareLastPair
发送后。
React/Redux 不会以这种方式工作:您的组件将在调用后收到新的 props。
对于您的测试,我建议您在 componentDidUpdate
生命周期方法中调用 compareLastPair
,该方法在 prop 更改后调用。
关于javascript - Action 调度后无法获取新 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51656707/