javascript - 如何使用 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 状态,但现在没有必要(也许??)
有任何想法吗?
解决方案
您可以在不使用不需要使用的 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>
);
}
}
推荐阅读
- python - 如何修复python中的while语法错误?
- c# - 使用 Microsoft.Xrm.Tooling 创建服务和上下文
- assembly - 这个汇编代码是做什么的,C 代码会是什么样子?
- jquery - Bootstrap 模态第二次不触发 jQuery 函数
- node.js - 检测是否在Nodejs中添加而不是修改文件
- webgl - 无法使用 regl 在 Z 方向上绘制点
- c - 如何在C中不允许被零除
- ruby-on-rails - nil:NilClass RoR 的未定义方法“to_sym”
- java - 如何告诉 Eclipse 将我编译的包保存到另一个路径的位置?
- materialize - MaterializeCSS 默认打开所有可折叠的