从API获取数据到状态

时间:2017-12-19 23:15:18

标签: javascript reactjs api

我在 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"}]}

但是我得到的是空阵列和警告,如下所示:

  

与...的联系   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 {  }

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

感谢您的时间。

1 个答案:

答案 0 :(得分: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 }))

}