首页 > 解决方案 > 如何使用 React Redux 正确执行加载屏幕

问题描述

我总是使用单个组件来加载屏幕,无论是Loading...文本还是某种微调器

然后将此组件导入并渲染应用程序,并将加载状态设置为 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 状态,但现在没有必要(也许??)

有任何想法吗?

标签: javascriptreactjsreduxloading

解决方案


您可以在不使用不需要使用的 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>
    );
  }
}

现场演示


推荐阅读