javascript - 为什么当我通过 fetch API 请求记录我的 React 状态 setState 时会收到两个响应?
问题描述
我从我在 React 中的状态的 console.log() 收到两个响应。第一个是空的,第二个包含我要打印的数据。
[] 空数组
[{...}] 0: {id: 1, date: "2011-07-01T10:30:30.000Z", name: "John"} 长度: 1 proto : Array(0)
我的代码如下:
constructor(props){
super(props);
this.state = {
session: []
}
}
componentDidMount(){
this.fetchSessionData();
}
fetchSessionData = () => {
fetch(`http://localhost:3000/sessions/${this.props.match.params.id}`)
.then(response => response.json())
.then(session => this.setState({session:session});
}
render()
{
console.log(this.state.session);
return(
<div>
<p>Hello world + {this.props.match.params.id}</p>
</div>
)
}
如果我的响应中有多个 javascript 对象,我还会看到类似的内容:
[] 空数组
[{…}] 0: {id: 1, date: "2018-11-01T10:30:30.000Z", name: "John"} 长度: 1 proto : Array(0)
[{…}] 0: {id: 1, date: "2018-11-01T10:30:30.000Z", name: "John"}, {id: 1, date: "2018-07-22T12:37: 01.000Z”,名称:“史蒂夫”},长度:2, 原型:数组(0)
等等等等。我怀疑这与 Promises 或生命周期有关,但未能找到答案。此外,当我尝试访问状态值时this.state.session.id
,它返回未定义。这里发生了什么?
解决方案
您的控制台日志位于 render() 函数中,因此每次组件呈现(或重新呈现)时都会触发。那很正常。它在第一次加载时渲染,然后在完成获取数据和更新状态时重新渲染。
此外,this.state.session
是一个包含您的 json 对象的数组。所以你将不得不写类似this.state.session[0].id
推荐阅读
- apache-kafka - RocksDB in Kafka stream reporting no space when there is space available
- r - 从 R 中的大型数据集中获取年份的更快方法
- php - 无法在 yii1 的 cjuidatepicker 中更改用户视图的日期格式
- javascript - 使用 javascript document.cookie="domain=" v/s document.cookie="domain:" 设置 cookie 时域的差异
- gstreamer - 在 GStreamer 管道中更改帧速率两次
- django - 在 Django 模板中使用“in”运算符未按预期工作
- python - 绘制多条线超过 3 个回顾日期的库存百分比变化
- laravel - 从项目网格中获取 Id 并保存到变量中
- java - BaseAdapter 在 notifyDataSetChanged 更新时崩溃?
- nativescript - Nativescript Tabview is not rendered at all but there is no exception/error either