钩在嵌套组件中

时间:2019-06-30 10:11:17

标签: reactjs react-hooks

我有一个包含以下内容的仪表板组件:

const AdminDashboard = () => {
const { page } = useDashboard();
...
<List>
  <Sidebar />
</List>
...
<Container maxWidth="lg" className={classes.container}>
  {page}
</Container>

我在侧边栏中

const Sidebar = () => {
  const { navigateTo } = useDashboard();

  return (
    <div>
      <ListItem button>
        <ListItemIcon onClick={() => navigateTo(<Category />)}>
          <DashboardIcon />
        </ListItemIcon>
        <ListItemText primary="Dashboard" />
      </ListItem>
export const DashboardContext = createContext<DashboardContextInterface | null>(
  null
);

const DashboardProvider = ({ children }: ProviderProps): JSX.Element => {
  const [page, setPage] = useState<JSX.Element>(Home);

  const navigateTo = (newPage: JSX.Element) => setPage(newPage);

  return (
    <DashboardContext.Provider value={{ page, navigateTo }}>
      {children}
    </DashboardContext.Provider>
  );
};

export const useDashboard = () => {
  const context = useContext(DashboardContext);
  if (context === null)
    throw new Error('useAuthState must be used within a AuthProvider');

  return context;
};

我认为这就是给我带来错误的原因

Warning: Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function.
    in DashboardProvider (at App.tsx:31)
    in MuiPickersUtilsProvider (at App.tsx:30)
    in AuthProvider (at App.tsx:29)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.tsx:28)
    in App (at src/index.tsx:7)

有没有办法使这项工作正常进行?我希望侧边栏中的按钮决定在仪表板容器中显示什么内容

这是app.tsx

const App: React.FC = () => {
  return (
    <Router>
      <AuthProvider>
        <MuiPickersUtilsProvider utils={LocalizedUtils} locale={nlLocale}>
          <DashboardProvider>
            <AdminRoute exact path="/dashboard" component={AdminDashboard} />
          </DashboardProvider>
          <Page exact path="/" component={Home} />
          <Page exact path="/login" component={Login} />
          <Page exact path="/register" component={Register} />
          <Page exact path="/products" component={Products} />
          <UserRoute exact path="/profile" component={Profile} />
        </MuiPickersUtilsProvider>
      </AuthProvider>
    </Router>
  );
};

0 个答案:

没有答案