javascript - 从 API 获取数据到状态

标签 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"}]}

但是我收到空数组和警告,如下所示:

The connection to ws://localhost:3000/sockjs-node/321/uglf2ovt/websocket was interrupted while the page was loading.

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 {  }

我不知道出了什么问题,为什么变量是空的?

感谢您的宝贵时间。

最佳答案

对于无法获取数据的问题,请在构造函数中绑定(bind)您的方法。

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

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

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 }))

}

关于javascript - 从 API 获取数据到状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47896571/

相关文章:

javascript - 在 Javascript 中用参数替换局部变量是否会影响性能?

javascript - 有没有办法用 jquery 将元素移出其父元素?

reactjs - 如何使用 React 和 TypeScript 创建通用箭头函数

javascript - react 空闲定时器: Video Player Activity Detected as Idle

android - api的问题

javascript - 将代码与其他脚本(命名空间)隔离

php - 在 HTML 文本字符串中插入隐藏字符?

reactjs - react-grid-layout 如何调整网格上组件的大小?

api - Yii2 API 身份验证 Behaviours() 不起作用

ios native 应用程序与 API 或直接数据库连接交谈?