首页 > 解决方案 > 为什么当我通过 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,它返回未定义。这里发生了什么?

标签: javascriptreactjsfetch

解决方案


您的控制台日志位于 render() 函数中,因此每次组件呈现(或重新呈现)时都会触发。那很正常。它在第一次加载时渲染,然后在完成获取数据和更新状态时重新渲染。

此外,this.state.session是一个包含您的 json 对象的数组。所以你将不得不写类似this.state.session[0].id


推荐阅读