我有一个像这样的初始 redux 状态:
{
loggedInUserId: null,
comments: []
}
这是我的 React 应用程序的样子:
class App extends Component {
componentWillMount() {
this.props.getLoggedInUserId();
}
render() {
return (
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/comments" component={Comments} />
</Switch>
);
}
}
在我的应用程序中,我调度一个操作 getLoggedInUserId()
,该操作异步填充状态中的 loggedInUserId
。
主页是一个显示一些文本的愚蠢组件。我启动应用程序(路径现在为“/”),查看主页组件,然后导航到评论页面,其中包含:
componentWillMount() {
this.props.fetchComments(this.props.loggedInUserId); // Dispatch action to do API call to fetch user's comments
}
render() {
// Show this.props.comments nicely formatted
}
一切正常,我在评论组件中看到了评论列表。
但是如果我刷新路由 /comments
上的页面,那么当 Comments 运行 componentWillMount 时,loggedInUserId 尚未加载,因此它将调用 fetchComments(null)
.
现在,为了解决这个问题,我正在评论组件中执行以下操作:
componentWillMount() {
if (!this.props.loggedInUserId) return;
this.props.fetchComments(this.props.loggedInUserId);
}
componentWillReceiveProps(nextProps) {
if (!this.props.loggedInUserId && nextProps.loggedInUserId) {
nextProps.fetchComments(nextProps.loggedInUserId);
}
}
效果很好。但我在 10 多个组件中完成此操作,似乎需要分解大量工作,但我没有找到一种优雅的方法来完成它。
所以我想问一下,遇到这种情况,你一般是怎么处理的?欢迎任何想法:
- HOC
- 副作用
- 其他图书馆
最佳答案
我正在使用Route
的包装器,它检查用户是否登录,如果没有,则将他们重定向到登录页面。仅在获取经过身份验证的用户的 userId 后才会呈现包装的路由。
import * as React from 'react'
import { Route, Redirect } from 'react-router-dom'
import URLSearchParams from 'url-search-params'
class AuthRoute extends React.Component {
componentDidMount() {
if (!this.props.isLoading) {
this.props.getLoggedInUserId()
}
}
render() {
if (this.props.isLoading) {
// first request is fired to fetch authenticated user
return null // or spinner
} else if (this.props.isAuthenticated) {
// user is authenticated
return <Route {...this.props} />
} else {
// invalid user or authentication expired
// redirect to login page and remember original location
const search = new URLSearchParams({
next: this.props.location.pathname,
})
const next =
this.props.location.pathname !== '/' ? `?${search.toString()}` : ''
return <Redirect to={`/login${next}`} />
}
}
}
您需要更新处理 getLoggedInUserId
操作的 reducer ,以存储 isLoading
状态。
关于reactjs - 设置状态变量后立即调度操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47952384/