javascript - 什么时候应该在 redux 中调度异步操作?

标签 javascript reactjs redux

在不同的 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/

相关文章:

javascript - 缓冲区.js :246 "Object 1 has no method ' toLowerCase'

javascript - 我如何过滤数组并返回正确的属性?

javascript - 无法识别 reactJS 框架 mouseOver 和 mouseEnter,但 onClick 工作正常

reactjs - 将组件与 connect() 一起使用 - 无法读取未定义的属性 'displayName'

javascript - 根据外部ID在javascript中对数组进行排序

javascript - 如何搜索具有多个值的单个单元格

javascript - HTML 中定义的 SVG 标签与 D3 添加的标签

reactjs - 在复选框单击上 react 更新获取

javascript - React Router - BrowserHistory.Push VS。上下文类型

reactjs - 快速连续调度相同的 redux 操作