目前,我在运行我的 saga 时以 JSON 格式从 API 获取数据。当组件挂载时,获取过程开始。这意味着组件渲染两次。
现在,当数据作为道具可用时。我可以使用它来渲染它。
我的方法如下,我有一个:
- 具有初始状态的构造函数
- 我在“componentDidMount”中获取数据
- 我有一个函数,它从 props 中获取 JSON 属性并将其放入新变量中
- 当道具包含获取的数据时,我在我的 render() 函数中运行此函数
这种方法的问题:一旦组件运行数据变成“结构化”的函数,渲染函数就会循环,然后在一段时间后,属性的值会在控制台中显示警告消息。
我的问题:
- render() 运行一次时如何防止循环?
- 我该如何设计这个,以便获取对象的特定属性合并到一个新对象中,以及如何
我希望我描述了关于我的问题的最重要的事情。这是代码:
class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
deviceInfo: {
name: "Initial Name",
batLevel: "78%",
}
}
}
componentDidMount() {
this.props.requestApiData();
}
updateDeviceInfoWithState (){
const devices = (this.props.data.data);
if(devices){
const newDeviceInfo = this.state.deviceInfo;
newDeviceInfo.name = devices[0].shadow.desired.payload.refAppData.name;
newDeviceInfo.batLevel = devices[0].shadow.reported.payload.refAppData.batteryState.level;
this.setState({
deviceInfo: newDeviceInfo,
});
}
}
render() {
this.updateDeviceInfoWithState()
return (
<div className='container'>
<p> {this.state.deviceInfo.name} </p>
<p> {this.state.deviceInfo.batLevel} </p>
</div>
)
}...