【问题标题】:Updating a state from another React component in ReactJS从 ReactJS 中的另一个 React 组件更新状态
【发布时间】:2022-01-19 23:40:50
【问题描述】:

我在 App.js 组件中有一个 api 调用,我从这里获取用户名以在导航栏中显示它。您可以看到导航栏组件将 name 属性作为参数传递给它。这就是我的 App.js 代码的样子

function App() {

  const[name,setName] = useState(null);

  useEffect(()=> {

    (
        async () => {
          try{
            const res =  await fetch('https://localhost:44361/api/users/getuser', {
                headers: {"Content-Type": 'application/json;charset=UTF-8'},
                credentials: 'include',
            });
            const content = await res.json();
            console.log(content);
            setName(content[0].uFirstName); // has to be content[0]
          }
          catch(e){
            console.log(e);
          }
        }
    )();
  },[name])
return (
    
     <Router>
       <div className="App">

           <Navbar name = {name}/>

           <Routes>

            <Route exact path="/" element={ <Home />} />

            <Route path="/registration" element = {<Registration/>} />

            <Route path="/login" element = {<Login/>} />

           </Routes>
      </div>
     </Router>
  );
}

export default App;

现在我想更新 Login.js 组件的 name 属性。 Login.js 看起来像这样:

function Login() {
    
    // const[name,setName] = useState(null);
    const[UEmail,setEmail] = useState(null);
    const[UPassword,setPassword] = useState(null);
    const[navigate, setNavigate] = useState(false);

    const submitHandler = async (e) => 
    {
        e.preventDefault(); // Prevent from being refreshed. Because User will not re-put every field if some field is wrong
        try{
            const res = await fetch('https://localhost:44361/api/users/login', {
                method: 'POST',
                headers: {"Content-Type": 'application/json;charset=UTF-8'},
                credentials: 'include',
                body : JSON.stringify({
                    UEmail,
                    UPassword
                })
            });

            var content = await res.json();

            if(res.status === 200)
            {
                  setNavigate(true);
                 //DO something
            }

            else if(res.status === 400){
                //DO something
            }
            
        }catch(err){
            console.log(err);
        }
    }
    if(navigate) // REDIRECT TO LOGIN PAGE AFTER BEING SUCCESSFULLY REGISTERED
    {
        return <Navigate to="/"/>
    }
    return (
        <div className="fullContainer">
            <div className="base-container">
                <div className="reg">Login</div>
                <div className="content">
                    <div className="form">
                        <div className="form-group">
                        
                            <input name="Email" type="email" placeholder="Email" required
                            onChange={e => setEmail(e.target.value)}
                            />
                        </div>
                        <div className="form-group">
                        
                            <input name="Password" type="password" placeholder="Password" required
                            onChange={e => setPassword(e.target.value)}
                            />
                        </div>
                    </div>
                </div>
                <div className="footer">
                    <button onClick={submitHandler} type="button" className="btn">Login</button>
                </div>
                <div className="toReg">
                <p>Don't have an account? 
                    <Link to="/registration">
                        <a> Register</a>
                    </Link>
                </p>
                </div>
            </div>
            </div>
    )
}

export default Login

用户在输入所有凭据后单击登录按钮后如何更新 App.js 中的名称。我想这样做是因为,在状态代码为 200 时将用户导航到主页后,导航栏中的用户名没有改变。我需要重新加载才能在导航栏中看到正确的用户名。

谢谢。

【问题讨论】:

    标签: javascript reactjs api react-navigation react-component


    【解决方案1】:

    更简单的方法是使用上下文。创建一个文件并在该文件中添加您想要在项目中更改/使用的变量,然后将您的项目包装在上下文中,最后在您不会使用 useContext from 'react' 的文件中调用该方法或变量。

    你会在这里找到你需要的一切:https://www.toptal.com/react/react-context-api

    【讨论】:

      【解决方案2】:

      将回调 setName 从 App 传递给 Login 组件。

      改变功能:

      function Login({setName}) {
      

      并传递回调:

      <Login setName={setName} />
      

      现在你可以在 Login 组件中调用 setName

      【讨论】:

        猜你喜欢
        • 2017-10-06
        • 2021-10-06
        • 2016-05-12
        • 2020-07-01
        • 1970-01-01
        • 2017-11-05
        • 2020-06-05
        • 1970-01-01
        • 2020-05-13
        相关资源
        最近更新 更多