我正在开发一个小型 react 应用程序,其中包含图表组件和一些其他组件。图表组件是一个单独的文件/组件/子组件。当我单击主容器中的按钮时,它会调用一个 promise (使用 axio)并返回一些数据作为响应。此响应数据设置为状态,并且该状态作为 Prop 传递给图表组件。但图表未加载。这是因为图表已经被加载,因为初始状态为空时图表也是空的。有没有办法只在 Promise 返回数据后渲染图表组件?
这是我的代码
按钮点击事件
ClickMe = () =>{
axios.get('http://xyzsdsd.com/abc')
.then((response)=>{
this.setState({
tags:response.data
});
console.log(this.state.tags);
}).catch((err)=>{
console.log(err);
});
}
渲染函数
render(){
return(
<div>
<otherComponents/>
<chart data={this.state.tags}/>
</div>
);
}
最佳答案
在渲染中添加一个条件,以便仅在 state.tags 对象有效时渲染图表组件。初始渲染时,不会渲染图表。当您的 AJAX 调用返回并调用 setState() 时,将使用非空 state.tags 再次调用 render() ,从而呈现您的图表。
render(){
let chart;
if (this.state.tags) {
chart = <chart data={this.state.tags}/>;
}
return (
<div>
<otherComponents/>
{chart}
</div>
);
}
关于javascript - 从按钮单击事件渲染 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40534007/