【问题标题】:Why functional component does not rerender after change of the state in useReducer()为什么在 useReducer() 中更改状态后功能组件不重新渲染
【发布时间】:2021-08-18 13:20:55
【问题描述】:

我使用 react Hooks,尤其是 useReducer。状态改变,但功能组件不会重新渲染。 应在按下菜单中的按钮后打开抽屉。状态改变,但抽屉没有打开。

这是沙盒代码https://codesandbox.io/s/affectionate-cdn-o0e6u?file=/src/drawer/drawer.tsx

const Drawer: FC = () => {
  const [state, dispatch] = useReducer(serviceReducers, serviceState);

  const drawerClose = () => {
    dispatch({ type: ActionTypes.OPEN_DRAWER, payload: false });
  };

  const drawer = (
    <div>
      <IconButton onClick={drawerClose}>
        <CancelPresentationIcon />
      </IconButton>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod            
      </p>
    </div>
  );
  return (
    <nav>
      <Drawer
        anchor={"left"}
        open={state.drawer}
        onClose={drawerClose}
        ModalProps={{
          keepMounted: true
        }}
      >
        {drawer}
      </Drawer>
    </nav>
  );
};

这是减速器

export enum ActionTypes {
  OPEN_DRAWER = "openDrawer"
}
export interface ServiceState {
  drawer: boolean;
}
interface OpenDrawer {
  type: ActionTypes.OPEN_DRAWER;
  payload: boolean;
}
export type ServiceActions = OpenDrawer;

export const serviceState = {
  drawer: false
};

export function serviceReducers(
  state: ServiceState,
  action: ServiceActions
): ServiceState {
  switch (action.type) {
    case ActionTypes.OPEN_DRAWER:
      return {
        ...state,
        drawer: action.payload
      };

    default:
      return state;
  }
}

【问题讨论】:

标签: reactjs typescript react-hooks use-reducer


【解决方案1】:

这里你需要使用上下文 API 到https://reactjs.org/docs/context.htmluseReducer() 管理和操作单个组件的状态。您需要使用 Context API 使用 Props Drilling 技术。使用 useReducer() 你不能调用其他组件 useReducer() 动作。如果你使用 redux,那么你应该使用 redux 来管理它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2020-05-04
    • 2020-07-28
    • 2020-03-30
    • 2021-10-15
    • 2023-03-20
    • 2019-06-29
    相关资源
    最近更新 更多