React:将对象添加到数组中
React : Add an object into an array
我是 React 初学者,我想将一个对象添加到数组中。
这是我的代码:
const initialState =
{
messages: [],
};
export default (state = initialState, action) => {
switch (action.type) {
case 'ADD_MESSAGE':
return {
messages: update(state.messages, {$push: [{text: action.text}]})
};
default:
return state
}
}
在我的组件中:
<ul>{this.props.chat.messages.map((message) =>{ return <li>{message.text}</Link></li> })
}
我收到错误:
Encountered two children with the same key,
[对象对象]. Child keys must be unique; when two children share a key, only the first child will be used.
感谢您的帮助。
您必须为每个列表项提供 unique keys。您的消息没有 key/ID,您需要提供唯一生成的 ID,或者作为最后的手段,使用索引(应尽可能避免使用)。上面的代码可以重构为:
{ this.props.chat.messages.map((message, index) => (<li key={index}>{message.text}</li>) }
根据定义,数组是不可变数据。
遵循最佳实践,优先使用$splice方法。
我是 React 初学者,我想将一个对象添加到数组中。
这是我的代码:
const initialState =
{
messages: [],
};
export default (state = initialState, action) => {
switch (action.type) {
case 'ADD_MESSAGE':
return {
messages: update(state.messages, {$push: [{text: action.text}]})
};
default:
return state
}
}
在我的组件中:
<ul>{this.props.chat.messages.map((message) =>{ return <li>{message.text}</Link></li> })
}
我收到错误:
Encountered two children with the same key,
[对象对象]. Child keys must be unique; when two children share a key, only the first child will be used.
感谢您的帮助。
您必须为每个列表项提供 unique keys。您的消息没有 key/ID,您需要提供唯一生成的 ID,或者作为最后的手段,使用索引(应尽可能避免使用)。上面的代码可以重构为:
{ this.props.chat.messages.map((message, index) => (<li key={index}>{message.text}</li>) }
根据定义,数组是不可变数据。
遵循最佳实践,优先使用$splice方法。