首页 > 解决方案 > 如果用户被 redux 商店“未经身份验证”,则呈现登录页面

问题描述

我有一个使用 redux 来发送身份验证信息的应用程序设置,但我不确定如何根据用户是否“加载”/身份验证来正确呈现内容。

应用组件(应用的入口点是一个基本的 React index.js):

class App extends Component {
  componentDidMount() {
    store.dispatch(loadUser())
  }
  render() {
    return (
      <Provider store={store}>
        <div className="App">
          {/* If there is a 401 error or the user isn't authenticated render the login page */}
          {/* If the user is authenticated and there is a token in the store render content */}
        </div>
      </Provider>
    );
  }
}

加载用户函数:

export const loadUser = () => (dispatch, getState) => {
  // User loading
  dispatch({
    type: USER_LOADING
  })
  axios.get('/users/user', tokenConfig(getState))
    .then(res => {
      dispatch({
      type: USER_LOADED,
      payload: res.data
    })}
    )
    .catch(err => {
     // console.log(err)
      dispatch(returnErrors(err.response.data, err.response.status))
      dispatch({
        type: AUTH_ERROR
      })
    })
}

我想实现我在 App 评论中提出的逻辑。

根据我对 redux 的了解,组件总是会先渲染,然后在 redux 的商店更新时,组件将被更新/重新渲染。我如何实现这一目标?

我尝试过使用 componentDidUpdate、getDerivedStateFromProps 和其他生命周期方法,但我无法弄清楚

标签: javascriptreactjsredux

解决方案


推荐阅读