reactjs - 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
已更改,因此不会重新渲染。
您必须将您的组件“连接”到商店,请参阅此文档。
推荐阅读
- python - 如何在 python 中拆分一个列表,知道它的子列表?
- python-3.x - 如何访问 Python 3 中函数外部的函数内部定义的变量?
- python - Keras Tensorflow 中的加权样本损失
- unreal-engine4 - 虚幻控制占有问题
- python - 如何使用 Numpy 获得一段时间?
- javascript - 如何使其每 5 分钟以角度触发/警报
- sql - 一段时间内的数字计数如何
- c# - VS2019 Comm 中的 microsoft.vsa.dll 错误,但在 VS2013 Pro 中没有
- angular - 如何使用 RxJS 和 Angular 发出变化?
- mariadb - MariaDB 性能根据 CPU 缓存