reactjs - 如何在 React 中创建一个结构来防止一个动作在完成之前传递给另一个动作?
问题描述
当我发出 api 请求时,我将返回的数据保存在 redux 存储中,然后在路由中使用这些数据。
我想要做的是在将组件安装到路由之前对其进行授权,但由于路由中未定义数据,我无法授权。特别是当我刷新页面时,它变得未定义。
那么如何防止在加载之前currentUser
渲染呢?Route
我应该如何解决这个问题?有解决问题的工具吗?
组件DidMount
componentDidMount(){
this.props.actions.getCurrentUser()
}
路由器
<Redirect to = "/" />
重定向到这个,因为currentUser
最初是未定义的
<Route exact path="/profile/:id/settings" render={(props) => {
var urlId = props.match.params.id;
return this.props.isLogged ? this.props.currentUser.id == urlId ? < ProfileSettings {...props} /> : <Redirect to={"/profile/" + urlId} /> : <Redirect to="/" />;
}
} />
反应还原
function mapDispatchToProps(dispatch) {
return {
actions: {
getCurrentUser: bindActionCreators(authAsyncActions.getCurrentUserApi, dispatch)
}
}
}
function mapStateToProps(state) {
return {
isLogged: state.isLoggedReducer,
currentUser: state.currentUserReducer,
isOwner: state.isOwnerReducer
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
获取当前用户接口
export function getCurrentUserApi() {
return async (dispatch, getState) => {
if (localStorageHelper.isExistsToken()) {
if (Object.keys(getState().currentUserReducer).length == 0) {
await axios.get(CURRENT_USER_PATH, {
headers: localStorageHelper.authHeaderObj()
}).then(res => {
dispatch(authActionsCreators.currentUserSuccess(res.data))
dispatch(authActionsCreators.isLoggedTSuccess())
}).catch(err => {
if (err.response.status === 401) {
var refreshToken = bindActionCreators(refreshTokenApi, dispatch)
refreshToken();
}
})
}
}
}
}
解决方案
推荐阅读
- c# - 使用 UWP 应用连接到 Facebook
- java - 春季子查询
- angular - 当我在确认窗口中单击取消时,mat-slide-toggle 不应更改其状态
- android - 如何更改工具栏标题的字体?
- python - 使用熊猫处理列中的缺失值
- jquery - 有没有办法像 Word 插件一样将 Excel 内容作为 HTML/Text 获取?
- javascript - VueJS Hotel Datepicker:通过事件侦听器获取选定日期的问题
- html - 引导固定表头的表头宽度
- flutter - 如何创建自定义信息 windows google map flutter?
- c++ - 有没有办法以编程方式设置磁盘签名,而不是磁盘部分