【发布时间】:2018-06-02 11:37:35
【问题描述】:
我在 App.js 中有这个:
constructor(props) {
super(props)
this.state = { data: 'false' };
this._getData = this._getData.bind(this);
}
componentDidMount() {
this._getData();
}
_getData = () => {
const url = 'http://localhost:8888/chats';
fetch(url, { credentials: 'include' })
.then((resp) => resp.json())
.then(json => this.setState({ chats: json.chats }))
}
render() {
return (
<div className="App">
{
// console.log(this.props);
this.state.chats &&
this.state.chats.map((item, key) =>
<div key={key}>
{item}
</div>
)
}
<Chat chats={this.state.chats} />
</div>
)
}
这是来自http://localhost:8888/chats的回复:
{"chats":[{"buddy":"x","lastMessage":"Hey how are you?","timestamp":"2017-12-01T14:00:00.000Z"},{"buddy":"y","lastMessage":"I agree","timestamp":"2017-12-03T01:10:00.000Z"}]}
我得到了这个:
对象作为 React 子对象无效(找到:带键的对象 {伙伴,lastMessage,时间戳})。如果你打算渲染一个集合 对于孩子,请改用数组。
in div (at App.js:40) // <div key={key}>
in div (at App.js:35) // <div className="App">
in App (at index.js:6) // ReactDOM.render(<App />,document.getElementById('root'));
它就在这一行
.then(json => this.setState({ chats: json.chats }))
我做错了什么?我读到有人这么说
不要将对象作为道具传递给 React.child。相反,将其作为 {...item} 传递,然后使用 props.{property} 进行访问,这可能会解决您的问题
但我不知道如何实现!
【问题讨论】:
-
数组的每个元素都是一个对象。如果要呈现消息,请执行
{item.lastMessage} -
@Li357 我是 React 的新手。你能解释一下我到底需要在哪里做 chage 吗?谢谢
-
@Li357 如果我还想传递其他项目,例如
buddy和timestamp怎么办? -
然后渲染多个元素。
-
@Li357 我现在仍然确定在哪里做
{item.lastMessage}。你的意思是有这样的东西<Chat chats={this.state.chats.lastMessage} />}?如果是这样,那是行不通的
标签: javascript arrays reactjs ecmascript-6