我在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 { }我不知道出了什么问题,为什么变量是空的?
耽误您时间,实在对不起。
发布于 2017-12-19 23:18:38
对于未获得任何数据时的问题,请将方法绑定到构造函数中。
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 }))
}https://stackoverflow.com/questions/47896571
复制相似问题