在不同的 redux 指南中,我看到了不同的调度 api 操作的方法。
例如,在 redux-reddit 应用程序中,异步操作是在 componentDidMount
函数中调度的:
class AsyncApp extends Component {
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.handleRefreshClick = this.handleRefreshClick.bind(this)
}
componentDidMount() {
const { dispatch, selectedSubreddit } = this.props
dispatch(fetchPostsIfNeeded(selectedSubreddit))
}
...
在现实世界中,异步操作的例子是在 componentWillMount
函数中调度:
function loadData(props) {
const { login } = props
props.loadUser(login, [ 'name' ])
props.loadStarred(login)
}
class UserPage extends Component {
constructor(props) {
super(props)
this.renderRepo = this.renderRepo.bind(this)
this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this)
}
componentWillMount() {
loadData(this.props)
}
那么,调度异步操作的正确方法是什么?还是无所谓?另外,据我所知,在 es6 类中,componentWillMount
函数被构造函数替换..
最佳答案
如果您正在构建同构应用程序(客户端和服务器渲染),您倾向于使用 componentDidMount
因为您只想从客户端和 componentDidMount
发出 ajax 调用仅在客户端运行。
关于javascript - 什么时候应该在 redux 中调度异步操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36719389/