[英]I cannot use useSelector() on React/Redux
I have the following code which I want to return the state to be used for private routes on React Router (allowing the access when isAuthenticated()
returns true).我有以下代码,我想返回 state 以用于 React Router 上的私有路由(当
isAuthenticated()
返回 true 时允许访问)。
import React from 'react'
import { useSelector } from 'react-redux'
export const isAuthenticated = () => {
const auth = useSelector(state => state)
return auth
}
But I'm getting this error:但我收到了这个错误:
Line 6: React Hook "useSelector" is called in function "isAuthenticated" which is neither a React function component or a custom React Hook function
I don't know how to fix it.我不知道如何解决它。 Does anyone know?
有人知道吗? Thanks
谢谢
Change your function name to be useIsAuthenticated
since you're creating a new custom hook.将您的 function 名称更改为
useIsAuthenticated
,因为您正在创建一个新的自定义挂钩。 custom hooks自定义挂钩
Hooks are only allowed to be used in the definition of other hooks (which have to start with "use") or in the implementation of functional react components.钩子只允许在其他钩子的定义中使用(必须以“使用”开头)或在功能性反应组件的实现中使用。 So either directly use it in a component
所以要么直接在组件中使用它
const component = () => {
const auth = useSelector(state => state)
return <div> {doSomethingWith(auth)} </div>;
}
or, if you intent to use your method isAuthenticated as a new hook, name it as Damian suggested或者,如果您打算使用您的方法 isAuthenticated 作为新钩子,请将其命名为 Damian 建议
const useIsAuthenticated = () => {
const auth = useSelector(state => state)
return auth
}
just turn it to react function component by只需转动它来反应 function 组件
export function isAuthenticated() {导出 function isAuthenticated() {
const auth = useSelector(state => state)
return auth
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.