【问题标题】:React auth using useState for route使用 useState 对路由进行 React auth
【发布时间】:2021-03-28 08:06:30
【问题描述】:

我正在尝试一个个人项目 学习 react 不要只使用 redux 钩子。 所以我有一个简单的自定义钩子

const useAuth = () => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  return { isAuthenticated, setIsAuthenticated };
};

用于将身份验证设置为 true

但它不起作用。

这里你可以看到一个例子

https://stackblitz.com/edit/react-rky7dn?file=src%2Flogin.js

谁能告诉我怎么了?

【问题讨论】:

标签: reactjs react-hooks


【解决方案1】:

您定义正确,但使用错误。 您只想在 App.js 中使用该钩子一次,然后将“setIsAuthenticated”传递给您的 Login.js(而不是再次调用该钩子)

//App.js
const { isAuthenticated, setIsAuthenticated } = useAuth();
...
<Route path="/login">{!isAuthenticated ? <Login setIsAuthenticated={setIsAuthenticated}/> : <Redirect from="/login" to="/" />}</Route>
//Login.js
const Login = ({setIsAuthenticated}) => {
....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-29
    • 2016-04-28
    • 2017-11-07
    • 1970-01-01
    • 2020-08-03
    • 2020-03-02
    • 2019-03-05
    • 2019-01-07
    相关资源
    最近更新 更多