我在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/