简体   繁体   English

重新渲染组件 ReactJs

[英]Re-render component ReactJs

I am new to react and creating some demo app I want to render my header component on the login user but somehow my app doesn't re-render the app.js component when I login with the user我是新来的反应和创建一些演示应用程序我想在登录用户上呈现我的 header 组件但不知何故当我与用户一起登录时我的应用程序不会重新呈现 app.js 组件

here is my app.js这是我的 app.js

function App() {

  return (
    <div className="app">
      <Router>
        <Header user={localStorage.getItem("user")} />
        <Switch>
          <Route path="/login">
            <LoginPage />
          </Route>
       </Switch>
    </Router>
  </div>
  );
}

note: I am saving my user in localStorage when I login into the app, please let me know if you need more info注意:当我登录应用程序时,我正在将我的用户保存在 localStorage 中,如果您需要更多信息,请告诉我

You can maintain the user data in state of App component and pass on the function to update user as props to the login component, once the user is logged in, call the function to update the user state. You can maintain the user data in state of App component and pass on the function to update user as props to the login component, once the user is logged in, call the function to update the user state. This will cause App component to rerender and subsequently update Header component.这将导致 App 组件重新渲染并随后更新 Header 组件。

Below is a sample implementation of how you can possible structure and write your code以下是如何构建和编写代码的示例实现

function App() {
  const [user, setUser] = useState(localStorage.getItem("user"));
  return (
    <div className="app">
      <Router>
        <Header user={user} />
        <Switch>
          <Route path="/login">
            <LoginPage setUser={setUser}/>
          </Route>
       </Switch>
    </Router>
  </div>
  );
}

function Login(props) {
   ...
   onUserLogin=() => {
     // Below is a mock implementation of a API service. You can use fetch or axios 
     Api.loginUser({...you params go here}).then(user => {
         props.setUser(user); // This updates the parent component with user state
     })

   }
   ....
}

localStorage doesn't trigger a re-render in React. localStorage不会触发 React 中的重新渲染。

You must have a global store to save the user data.您必须有一个全局存储来保存user数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM