我实现了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>
</>
);
}
答案 0 :(得分:0)
React无法知道外部变量state
已更改,因此无法重新呈现。
您必须将组件“连接”到商店,请参见this doc。
答案 1 :(得分:0)
const state: IGameState = useSelector((state: IGameState) => state);