javascript - 在 React 应用程序中重定向用户的最佳实践是什么?
问题描述
我在 React 应用程序中看到了更多与重定向用户相关的案例,每个案例都只是解决方案的不同方法。在某些情况下,在这样的操作中发生了重定向`
export const someAction = (values, history) => async dispatch => {
const res = await someAsyncOperation(props);
history.push('/home');
dispatch(someAction);
}
在此示例中,历史对象(表单 react-router)正在反应组件中传递。对我来说,这种方法是不可接受的。还有一个来自 react-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 返回的错误)。然后只有在没有错误的情况下才能实现重定向。
推荐阅读
- browser - MS Edge 14+ CSS 助手不起作用
- ios - 从文件中快速读取数据
- tomcat - 如何在 Tomcat 中将 java.util.Properties 配置为 JNDI
- c# - C# 中的 Outlook 加载项开发
- json - 在 Jmeter 中使用带有 != 条件的 JsonPath 从 JSON 中提取一些值
- forms - 使用数据库的 Laravel 搜索表单
- r - 在 r 中读取多个 *.rtf 文件
- android - ListView 滚动条样式在小部件中无法正常工作
- python - 熊猫读取具有不同列数的多个表
- ionic-framework - 在变量中导入 ionic3 字体