reactjs - 在使用 Redux 和 redux-thunk 的 React 应用程序中处理加载状态,在获取数据一次后返回到组件

标签 reactjs redux

我有一个使用 Redux 的 React 应用程序 redux-thunk 。给定需要从 API 获取信息的某个组件,我会调用绑定(bind)操作创建者以在安装后发出该请求:

componentDidMount() {
  this.props.fetchSomething();
}

为了让 UI 知道它是否处于加载状态,我使用 loading来自应用程序状态的变量。我的 reducer 处理 LOADING 的三种操作类型, SUCCESS ,和FAILUREloading变量设置为 trueLOADING发出 Action ;然后将其设置为 falseSUCCESSFAILURE .

因此 render 中有以下内容方法:

render() {
  if (this.props.loading) {
    return <Spinner />;
  }

  return (
    <div>
      This part uses the fetched data, available via this.props.something
    </div>
  );
}

因为最初this.props.somethingnull ,我还必须在渲染所需模板之前检查它是否存在,因此上面的 if 语句变为:

if (!this.props.something || this.props.loading) {
  return <Spinner />;
}

到目前为止,这种方法对我来说效果很好,但也存在一些问题,其中之一是:

The first time I access the page, this.props.something is not yet set. But the second time I access the page, with the app already loaded, that data had already been fetched once, so this.props.something will have been defined. Because of that, there is brief moment in which the if statement condition is FALSE and the actual component template gets rendered.

(1) 你们会如何解决这个问题?

(2) 通过您的方法,您将如何处理必须发出多个请求(例如其中五个请求)的组件,使用与上面相同的方法,但使用不同的 loading/something每个变量?我可以重复上面相同的方法,但会遇到已定义但未加载的每个资源的短暂 if 语句失败的问题。

最佳答案

1) 您有两个选择。您可以在 componentWillUnmount 上调度一些 RESET 操作并重置您的存储,this.props.something 将再次为 null。第二个选项是显示数据(如果您已有数据),显示微调器,并在第二次获取成功时将其合并在一起。 (取决于目的和用户界面)

2)我从来没有需要过它,但是如何将它存储在 redux 中作为映射 {componentName: returned} 并检查是否所有组件都已加载?

编辑:当您将 loading 的初始值设置为 true 时,您不需要检查某些属性。

关于reactjs - 在使用 Redux 和 redux-thunk 的 React 应用程序中处理加载状态,在获取数据一次后返回到组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47188186/

相关文章:

javascript - 使用 react-router 中的 MemoryRouter 使用 javascript 导航

javascript - async wait 返回 Promise 而不是值

javascript - 在 React 组件中发出渲染数组而不使用 return

reactjs - 我如何将 react 添加到我的 laravel 项目?

reactjs - 在 React.js 中,使用 flexGrow 时得到错误的 clientHeight

javascript - Express.js : respond with image file instead of binary file?

javascript - 如何将 setInterval 与 redux-thunk 一起使用?

javascript - React TypeError : _this2. props.variations.find 不是函数

javascript - Web应用程序使用Redux,如何处理逻辑只需要执行一次

reactjs - 发送 Action 后的 Redux Thunk 回调?