在路由组件中管理用户状态

So I have some routes in a route.js file that are called in React.render() inside index.jsx.

routes.js

export default (
 <BrowserRouter>
   <Route path='/'>
     <LandingPage/>
   </Route>
   <Switch>
     <Route path="/login">
       <Login/>
     </Route>
     <PrivateRoute path="/home">
       <UserApp/>
     </PrivateRoute>
   </Switch>
  </BrowserRouter>
);

index.jsx

import routes from './routes';

ReactDOM.render(routes, document.getElementById("app"));

以上工作正常。

However, as I have progressed through development, I need to handle user authentication, so I want to manage userContext and useState. How can I convert routes.js to an exported function or component that I can call from index.jsx? Something similar to the following:

adapted routes.jsx

const AppRouter = () => {
  const [value, setValue] = useState('hello from context');

  return(
    <BrowserRouter>
      <Route path='/'>
          <LandingPage/>
      </Route>
      <Switch>
        <UserContext.Provider value={{value, setValue}}>
          <Route path="/login">
            <Login/>
          </Route>
        </UserContext.Provider>
        <PrivateRoute path="/home">
          <UserApp/>
        </PrivateRoute>
      </Switch>
    </BrowserRouter>
  )
}

export default AppRouter;

adapted index.jsx

import AppRouter from "./routes";

ReactDOM.render(<AppRouter/>, document.getElementById("app"));

当我将AppRouter作为组件传递时(如上),我得到:

The above error occurred in the <AppRouter> component:
    in AppRouter

Consider adding an error boundary to your tree to customize error handling behavior.

Error: Minified React error #321; visit etc etc.

And if I make AppRouter a function (export default function AppRouter() {return( my varying routes) }), then React.render() complains that functions cannot be passed as a child element.

任何建议将不胜感激! 谢谢!

评论