我有一个反应成分:
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();
}
}
//...
}我的还原器发出同步操作:
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函数中调度之前相同的支持,尽管状态是由Redux更新的(您可以在图像的Redux-logger中看到它),并且clickedTiles数组应该由还原器来确定。
发布于 2018-08-02 15:04:46
即使你的调度行动是同步的(但我们不知道.您没有共享代码),React组件中的道具更新遵循正常的异步生命周期,而在分派之后显式地调用compareLastPair。
React/Redux不是这样工作的:新的道具将在调用后由组件接收。
对于您的测试,我建议您在compareLastPair生命周期方法中调用componentDidUpdate,这个方法在道具更改后调用。
https://stackoverflow.com/questions/51656707
复制相似问题