首页 > 解决方案 > 在 React 应用程序中重定向用户的最佳实践是什么?

问题描述

我在 React 应用程序中看到了更多与重定向用户相关的案例,每个案例都只是解决方案的不同方法。在某些情况下,在这样的操作中发生了重定向`

export const someAction = (values, history) => async dispatch => {
    const res = await someAsyncOperation(props);
    history.push('/home');
    dispatch(someAction);
}

在此示例中,历史对象(表单 react-router)正在反应组件中传递。对我来说,这种方法是不可接受的。还有一个来自 react-router的特殊重定向。

在那之后,我已经搜索了很多文章,找不到任何东西。那么在您看来,重定向的最佳实践是什么以及在哪里处理此类流程?

标签: javascriptreactjsreduxreact-reduxreact-router

解决方案


在 React 中,您通常在componentDidUpdate组件中实现重定向。

在异步操作的情况下,您将检查存储在 Redux 存储中的标志,通常是一个布尔值,如isFetching, isCreating, isUpdating, 等...,它将被操作修改。

简单的例子:

class EditUser extends Component {
  compondentDidUpdate(prevProps) {
    if (prevProps.isUpdating && !this.props.isUpdating) {
      // ↑ this means that the async call is done.

      history.push('/users')
    }
  }

  updateUser() {
    const modifiedUser = // ...

    this.props.updateUser(modifiedUser)
    // ↑ will change state.users.isUpdating from false to true during the async call,
    // then from true to false once the async call is done.
  }

  render() { 
    // ...
    <button onClick={this.updateUser}>Update</button>
    // ...
  }
}

const mapStateToProps = (state, props) => ({
  userToEdit: state.users.items.find(user => user.id === props.userId)
  isUpdating: state.users.isUpdating,
})

const mapActionsToProps = {
  updateUser: usersActions.updateUser,
}

export default connect(mapStateToProps, mapActionsToProps)(EditUser)

下一步通常是在您的 Redux 存储中添加另一个标志来跟踪异步调用是否成功(例如state.users.APIError,您可以在其中保留 API 返回的错误)。然后只有在没有错误的情况下才能实现重定向。


推荐阅读