【问题标题】:How to correctly do a loading screen using react redux如何使用 React Redux 正确执行加载屏幕
【发布时间】:2019-05-20 22:45:45
【问题描述】:

我总是使用单独的组件来加载屏幕,使用 Loading...text 或某种微调器

然后导入此组件并渲染应用程序,并将加载状态设置为 true,直到组件已安装并将状态更改为 false。但是我在这里遇到了一个问题,只能通过在组件确实挂载中设置超时来解决,我想避免这种情况,因为这意味着在某些情况下,应用程序的加载时间超过了必要的时间

请查看正在发生的事情的 GIF:https://makeagif.com/gif/-dyW3DE

它在显示更新部分之前将包显示为空闪烁。我想说加载正确,直到包是正确的 redux 状态,然后显示它

到目前为止的代码

  state = {
    isLoading: true,
  }

  componentDidMount(){
     this.setState({ isLoading: false })
  }


return isLoading ? ( <div> Loading... </div>) : (
    <div>
      <h4> Bag </h4>
      <Modal /> 
     // other bag stuff here
      <p> Bag total: £{this.bagTotal(bag.products)}</p>
    </div>
  )

我想最终将其移至 redux 状态,但现在没有必要(也许??)

有什么想法吗?

【问题讨论】:

  • 这个不需要redux。
  • @MohamedSameer 我知道,但为什么现在不起作用?

标签: javascript reactjs redux loading


【解决方案1】:

当你将它移动到 redux 时,只需调度函数来更改 isLoading 的值并使用 mapStateToProps 将状态连接到组件,当值在 store 中更新时,组件将自动显示加载栏

【讨论】:

    【解决方案2】:

    你可以在不使用不需要使用的 redux 的情况下做这件事。如果您拨打任何Http API request 或使用setTimeout

    import ReactDOM from "react-dom";
    import React, { Component } from "react";
    
    import "./styles.css";
    
    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          isLoading: true
        };
      }
    
      componentDidMount() {
        fetch("https://jsonplaceholder.typicode.com/todos")
          .then(response => {
            return response.json();
          })
          .then(response => {
            this.setState({ isLoading: false });
            console.log("response :", response);
          })
          .catch(error => {
            this.setState({ isLoading: false });
            console.log("error :", error);
          });
    
        //or using setTimeout
         setTimeout(
            function() {
             this.setState({ isLoading: false });
            }.bind(this),
           3000
         );
      }
    
      render() {
        let { isLoading } = this.state;
        return (
          <div>
            {isLoading ? (
              <div className="App">
                <h1>Loading...</h1>
              </div>
            ) : (
              <div className="App">
                <h1>Hello CodeSandbox</h1>
                <h2>Start editing to see some magic happen!</h2>
              </div>
            )}
          </div>
        );
      }
    }
    

    Live Demo

    【讨论】:

    • 啊,所以我用 redux 来做我的 axios 请求,所以我应该把它全部移到那里?
    • 你可以像这样管理,但它需要调度 redux 操作并管理它。
    猜你喜欢
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 2018-06-06
    • 2020-01-10
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多