我对 ReactJS 比较陌生。我真的很喜欢 React 呈现数据的方式。但是,当我开始使用异步调用来检索和呈现服务器端数据时,我发现有一些奇怪的行为。我有一个调用子组件并呈现服务器端数据的组件。
服务器端调用是异步调用。我的代码是这样的:
class myComponent extends component {
constructor(props) {
super(props);
this.componentDidMount = this.componentDidMount.bind(this);
this.state = {myVariable: []};
}
this.componentDidMount() {
fetch() => { server side async call to retrieve data
this.setState({myVariable: serverData});
}
render() {
<div className="myClass">
<div className="renderMyBox">
<div> {this.state.myVariable} </div>
</div>
</div>
}
}
我面临的问题是。前两个 div 立即在服务器上呈现,然后几乎有 1 秒的延迟,其中有一个空的 div,然后由于异步调用而设置状态。然后状态的变化触发重新渲染。
在异步调用成功并设置状态之前,有什么方法可以强制渲染不发生吗?有解决方法吗?
最佳答案
正如 elmaister 所指出的,在有数据之前您不能返回任何内容。这可以通过观察 isReady
变量来处理:
class myComponent extends component {
constructor(props) {
super(props);
this.componentDidMount = this.componentDidMount.bind(this);
this.state = { myVariable: [], isReady: false };
}
this.componentDidMount() {
fetch() => { server side async call to retrieve data
this.setState({
myVariable: serverData,
isReady: true
});
}
render() {
if (this.state.isReady) {
return <div className="myClass">
<div className="renderMyBox">
<div> {this.state.myVariable} </div>
</div>
</div>
}
}
}
关于javascript - 从异步服务器端数据调用渲染 ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39442505/