首页 > 解决方案 > 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>
    </>
  );
}

标签: reactjstypescriptredux

解决方案


React 无法知道外部变量state已更改,因此不会重新渲染。

您必须将您的组件“连接”到商店,请参阅此文档


推荐阅读