我有一个令人难以置信的烦人的问题,我的redux存储(似乎)没有及时更新,因为我猜测是某种React抢先优化。这是我的App组件
function mapStateToProps(store: FoAppState): AppState {
return {
isCurrentlySelectingARoad: store.isSelectingRoad,
};
}
function mapDispatchToProps(dispatch: Dispatch) {
return {
activateRoadSelects: (s: boolean) => {
return dispatch(activateRoadSelection(s));
},
};
}
const connector = connect(mapStateToProps, mapDispatchToProps);
type AppProps = ConnectedProps<typeof connector>;
class App extends React.Component<AppProps, {}> {
evaluateEndTurnEligibility() {
const { isCurrentlySelectingARoad } = this.props
// ** PROBLEM **
console.log(isCurrentlySelectingARoad);
if (
!isCurrentlySelectingARoad
) {
this.setState({
...this.state,
canEndTurn: true,
});
}
}
selectRoadSpotCB() {
this.props.activateRoadSelects(false);
const millisecondsToWait = 1000;
setTimeout(() => {
this.evaluateEndTurnEligibility();
}, millisecondsToWait);
}
}
render(){
<Road cb={selectRoadCB} />
}
道路组件
type Props = {
cb: Function;
};
type HPProps = {
tiles: Array<TileModel>;
};
function mapStateToProps(store: FoAppState): HPProps {
return {
tiles: store.boardToBePlayed.listOfTiles,
};
}
const connector = connect(mapStateToProps);
type ReduxProps = ConnectedProps<typeof connector>;
};
type HPProps = {
tiles: Array<TileModel>;
};
function mapStateToProps(store: FoAppState): HPProps {
return {
tiles: store.boardToBePlayed.listOfTiles,
};
}
const connector = connect(mapStateToProps);
type ReduxProps = ConnectedProps<typeof connector>;
type HighlightProps = ReduxProps & Props;
class Road extends Component<HighlightProps, {}> {
constructor(props: HighlightProps) {
super(props);
}
selectedARoadSpot(): void {
socket.emit(
"addRoad",
"1",
);
this.props.finishedSelectingCallback();
}
render() {
return (
<circle
onClick={this.selectedARoadSpot}
/>
);
}
}
export default connector(Road);
减速器
import { SelectingRoadAction, SELECTING_ROAD } from "../Actions";
export default function isSelectingRoad(
state: boolean = false,
action: SelectingRoadAction
): boolean {
switch (action.type) {
case SELECTING_ROAD:
console.log(action.isSelecting);
return action.isSelecting;
default:
return state;
}
}
问题在于,当某人单击“道路”时,它最终到达回调并转到“ evaluteTurnEligibility”,尽管控制台日志之前 if
说是false ,如果没有真正通过。出于某种原因,在valuateElg方法中添加等待一秒钟的超时实际上可以解决此问题。调度是同步的,所以我只是忽略了什么,还是React尝试为我优化内容的问题?
答案 0 :(得分:1)
我会在this.evaluateEndTurnEligibility()
生命周期内致电componentDidUpdate
(请记住以验证prevprops是否与下一个props不同)。
尝试访问给定功能的道具/状态时,提前状态发生变化通常会导致混乱。即使调度是同步的,React也会接收到新的更改道具,然后重新渲染,这一切都可能导致您在需要的时间没有下一个道具。