useSelector值在分派前返回

时间:2020-05-14 17:14:34

标签: reactjs react-redux

感谢阅读。

我有一个问题可以归结为:

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渲染组件时都会使用它。

当我在useEffect中执行调度时,此isAuthenticated值为true,但在第一个渲染组件中返回false。

我需要在分派执行时返回isAuthenticated true。

示例

  1. dispatch(boolUserVerify(headers))

  2. 选择新值 -之后-

  3. 渲染私人路线

RouterPrivate

3 个答案:

答案 0 :(得分:0)

| id | build_no | build_name | floor_no | floor_name | | --- | ------------- | ---------- | ------------- | ---------- | | 41 | BUILD40210011 | A | | | | 44 | BUILD40210013 | C | FLOOR40210002 | C1 | | 45 | BUILD40210013 | C | FLOOR40210003 | C2 | | 46 | BUILD40210012 | B | FLOOR40210004 | B1 | 返回从商店中选择的值。

useSelector在呈现组件之后运行:您已经使用useEffect

取得了一些价值

答案 1 :(得分:0)

挂钩不是根据条件评估的,而是根据执行顺序来评估的。此外,useEffect在初始渲染之后运行,因此到那时useSelector已经执行。

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

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

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}}}/>)
    )} />
  )

}

答案 2 :(得分:0)

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

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
  }