如何在子组件中设置变量以在 React 中的父组件中使用

问题描述

我的仪表板使用受保护的路由,我只希望登录的人能够看到仪表板。所以,在我的登录组件中,我正在获取数据,这是我检查用户的电子邮件密码是否正确的地方。所以我想要做的是将一个布尔变量发送到 index.js 的父元素,并根据我想向用户显示仪表板的值。 所以这是我的 index.js:

const hist = createbrowserHistory();
console.log(hist)
ReactDOM.render(
  <Router history={hist}>
    <Switch>
      <Route path="/" component={Login} exact />
      <ProtectedRoute path="/admin" component={(props) => <AdminLayout {...props} />} isAuth={true}/>
      <Route path="" component={() => "404 NOT FOUND"} />
    </Switch>
  </Router>,document.getElementById("root")
);

所以我想发送一个变量来检查,而不是里面的true,isAuth={true}。 还有我的登录组件:

const Login = ({ submitForm }) => {
  const [isSubmitted,setIsSubmitted] = useState(false);

  function submitForm() {
    setIsSubmitted(true);
  }
  const { handleChange,values,handleSubmit,errors } = useForm(
    submitForm,validate
  );

  const [loading,setLoading] = useState(false);
  const [error,setError] = useState(false);
  const [login,setLogin] = useState(false);

  const fetchLogin = async (email,password) => {
    try {
      setLoading(true);
      const res = await Axios({
        data: {
          user_email: email,user_password: password,},});
      if (res.status === 200) {
        setLogin(true);
        localStorage.setItem("user-info",JSON.stringify(res));
        
      }
      setLoading(false);
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  function loginButton() {
    fetchLogin(values.email,values.password);
  }
  return (
    <form>
      
    </form>
  );
};

export default Login;

非常感谢您的帮助...

解决方法

有不同的方法。

  1. 您可以在 user-info 中读取从 localStroage 检索 ProtectedRoute。在这种情况下,Login 除了 localStorage.setItem("user-info",JSON.stringify(res))
  2. 之外不需要做任何事情
  3. 您可以使用回调函数将登录状态传播到父组件。有关示例,请参阅 this question
  4. 如果您还想从其他组件访问登录状态,您可以考虑使用 React Context。 Here 就是一个例子。