使用中的值选择器在调度前返回



感谢您的阅读。

我有一个问题,归结为:

function PrivateRoutes ({component:Component, ...rest}){
const dispatch = useDispatch();
const [headers, setHeaders] = useState({
headers:{
'Content-Type': 'application/json',
'authorization': localStorage.getItem('sback_id')
}
})
useEffect(() => {
dispatch(boolUserVerify(headers));
} ,[dispatch, headers])
const {isAuthenticated} = useSelector(state => state.authe);
return (
<Route {...rest} render={props => (
isAuthenticated ? (<Component {...props}/>) : (<Redirect to={{pathname:'/register', state:{from:props.location}}}/>)
)} />
)
}

每次我第一次渲染组件时,它都会在执行调度之前使用 useSelector 获取初始值。

当我在使用效果中执行调度时,这是经过身份验证的值为真,但在第一个渲染组件中返回假。

我需要返回是经过身份验证的 当调度执行时。

  1. dispatch(boolUserVerify(headers((

  2. 选择新值 --后--

  3. 渲染专用路由

路由器专用

useSelector返回从存储中选择的值。

useEffect在渲染组件后运行:您已经使用useSelector获取了一些值

钩子不是根据条件进行评估的,而是作为执行顺序何时出现的。此外,useEffect在初始渲染之后运行,因此到那时useSelector已经执行

。您需要在减速器中添加加载状态。isLoading in reducer will be true的初始值。当您调度操作并且状态为更新时,您可以设置状态isLoading to false并发布评估 isAuthenticated 值。

但是,您不得在 PrivateRoute 中调度 boolUserVerify ,而是在呈现 PrivateRoutes 的父组件中调度。理想情况下,这将是您的顶级组件

function App () {
const dispatch = useDispatch();
const [headers, setHeaders] = useState({
headers:{
'Content-Type': 'application/json',
'authorization': localStorage.getItem('sback_id')
}
});
useEffect(() => {
dispatch(boolUserVerify(headers));
} ,[dispatch, headers])
const {isAuthenticated, isLoading} = useSelector(state => state.authe);
if(isLoading) {
return <Loader />; 
}
return <PrivateRoute path="/path" component={Component} />
}
function PrivateRoutes ({component:Component, ...rest}){
const {isAuthenticated} = useSelector(state => state.authe);
return (
<Route {...rest} render={props => (
isAuthenticated ? (<Component {...props}/>) : (<Redirect to={{pathname:'/register', state:{from:props.location}}}/>)
)} />
)
}

>您可以尝试添加到减速器加载值

state = {loading: true, isAuth: false, wrongAuth: false}
switch(state, action){
case SUCCESS_AUTH:
return{
loading: false,
auth: true
}
case FAILED_AUTH:
return{
loading: false,
auth: false,
wrongAuth: true
}
default:
return state
}

最新更新