【问题标题】:How to set variable in child component to use in parent in React如何在子组件中设置变量以在 React 的父组件中使用
【发布时间】:2021-09-07 17:56:18
【问题描述】:

我正在为我的仪表板使用受保护的路由,我只希望登录的人能够看到仪表板。因此,在我的登录组件中,我正在获取数据,这是我检查用户的电子邮件和密码是否正确的地方。所以我想要做的是将一个布尔变量发送到父元素 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")
);

所以我想发送一个变量来检查,而不是真正的里面,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;

感谢您的帮助...

【问题讨论】:

    标签: reactjs authentication parent protected


    【解决方案1】:

    有不同的方法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 2018-01-02
      相关资源
      最近更新 更多