从API获取数据到状态

问题描述 投票:0回答:1

我在App.js中有以下内容

  constructor(props){
      super(props)
      this.state = {data: 'false'};
  }



  componentDidMount(){
      this._getData();
  }



  _getData = () => {
      const url = 'http://localhost:8888/chats';

      fetch(url, { credentials: 'include' })
        .then((resp) => resp.json())
        .then(json => this.setState({ data: json.chats }))

  }

  render() {
      return (
           <div className="App">
              {
               this.state.chats &&
               this.state.chats.map( (buddy, key) =>
                  <div key={key}>
                    {buddy}
                  </div>
               )}
               <Chat />
           </div>
      )
  }

我在Chat.js中有这个

import React, { Component } from 'react';

class Chat extends Component {
    render() {
        console.log(this.props);
        return (
            <div className="App">
                MY Chat
            </div>
        );
    }
}

export default Chat;

我在我的http://localhost:8888/chats中有这个

{"chats":[{"buddy":"x","lastMessage":"Hey how are you?","timestamp":"2017-12-01T14:00:00.000Z"},{"buddy":"y","lastMessage":"I agree, react will take over the world one day.","timestamp":"2017-12-03T01:10:00.000Z"}]}

但是我得到的是空数组和一个waring如下:

在加载页面时,与ws:// localhost:3000 / sockjs-node / 321 / uglf2ovt / websocket的连接被中断。

Object {  }
mutating the [[Prototype]] of an object will cause your code to run very slowly; instead create the object with the correct initial [[Prototype]] value using Object.create
Object {  }

我不确定有什么问题,为什么变量是空的?

谢谢你的时间。

javascript reactjs api
1个回答
3
投票

对于没有获取任何数据的问题,请在构造函数中绑定您的方法。

constructor(props) {
    super(props)
    this.state = { chats: 'false'};
    this._getData = this._getData.bind(this);
}

此外,您没有将任何道具传递给聊天组件。例如,您可以这样做:

render() {
    return (
        <div className="App">
           {
            this.state.chats &&
            this.state.chats.map( (buddy, key) =>
                <div key={key}>
                    {buddy}
                </div>
            )}
            <Chat chats={this.state.chats} />
        </div>
     );
}

所以当你在做console.log时

class Chat extends Component {
  render() {
    console.log(this.props); // Here you will have an object like { chats: [data] }
    return (
      <div className="App">
      MY Chat
      </div>
    );
  }
}

编辑:统一状态属性,您应该在方法中更改它:

_getData = () => {
    const url = 'http://localhost:8888/chats';

    fetch(url, { credentials: 'include' })
        .then((resp) => resp.json())
        .then(json => this.setState({ chats: json.chats }))

}
© www.soinside.com 2019 - 2024. All rights reserved.