React Redux,存储调度未触发组件更新



我实现了React Redux,但smthn是错误的,但我不明白到底是什么。有什么想法吗?我正在更改状态,但值仍然不变。我尝试过useStore((,但它需要0个参数。我哪里错了?如果方法store.getState((返回的不是引用,我该如何获取状态。

页面

GameStore.subscribe(() => GameStore.getState().number);
let state = GameStore.getState();
GameStore.subscribe(() => state = GameStore.getState());
const MainPage = (props: any) => {
return (
<>
<Card style={{ margin: 15 }} elevation={1}>
<CardHeader title="Controls"></CardHeader>
<CardContent>
{state.number}
</CardContent>
<CardActions>
<Button variant="contained" color="primary"
onClick={() => GameStore.dispatch({type: "DECREMENT_NUMBER", payload: 1})}>
-
</Button>
<Button variant="contained" color="primary"
onClick={() => GameStore.dispatch({type: "INCREMENT_NUMBER", payload: 1})}>
+
</Button>
</CardActions>
</Card>
</>
);
};
export default MainPage;

存储

import { createStore, Reducer, PreloadedState } from 'redux';
interface IGameState {
number: number;
}
interface IActionIncrement {
type: "INCREMENT_NUMBER";
payload: number;
}
interface IActionDecrement {
type: "DECREMENT_NUMBER";
payload: number;
}
type GameAction = IActionIncrement | IActionDecrement;
const gameInitialState: PreloadedState<IGameState> = { number: 0 };
const gameReducer: Reducer<IGameState, GameAction> = (state: IGameState | undefined, action: GameAction): IGameState => {
if (!state) {
return gameInitialState;
}
switch (action.type) {
case "INCREMENT_NUMBER":
return { ...state, number: state.number + action.payload }
case "DECREMENT_NUMBER":
return { ...state, number: state.number - action.payload }
default:
return state
}
}
export const GameStore = createStore(gameReducer, gameInitialState);

应用程序

const App = () => {
return (
<>
<Provider store={GameStore}>
<HeaderCmp/>
<MainPage/>
{/*<FirstVarCmp/>*/}
</Provider>
</>
);
}
React无法知道外部变量state已更改,因此不会重新应答。

你必须";"连接";您的组件到商店,请参阅此文档。

const state: IGameState = useSelector((state: IGameState) => state);

最新更新