this.state = {
post: {
question: '',
img: '',
postId: '',
userId: ''
},
feed: [],
}
将对象添加到数组的最佳做法是什么。
答案 0 :(得分:2)
首先,您需要对state
进行一些更正:
this.state = {
posts: [],
feeds: [],
}
将来帖子将是Array of Objects
,例如:
this.state = {
posts: [
{ postid: 1, question: "question" },
{ postid: 2, question: "question" }
]
}
使用this.setState
为帖子添加新帖子,同时请注意state
不可变:
const newpost = { id: 1, question: "question" };
this.setState({
posts: this.state.posts.concat(newpost)
// or with rest operator posts: [...this.state.posts, newpost]
})
有关state
React State
示例 JSFiddle
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
feed: [],
}
}
getName = () => {
const names = ['One', 'Two', 'Three', 'Four', 'Five', 'Six']
const random = Math.floor(Math.random() * names.length);
return names[random]
};
getId = () => Math.floor(Math.random() * (9999-1)) + 1;
makePost = () => ({ id: this.getId(), name: this.getName() });
createPost = () => {
this.setState({
// Rest operators ensure a new object with merged properties and values.
// Requires the "transform-object-rest-spread" Babel plugin
posts: [...this.state.posts, this.makePost()]
// Or like this: this.state.posts.concat(this.makePost())
})
};
render() {
return (
<div>
<button onClick={this.createPost}>Create Post</button>
<pre>
{JSON.stringify(this.state, null, 2)}
</pre>
</div>
);
}
}
ReactDOM.render(
<Example />,
document.getElementById('container')
);
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>