【发布时间】:2019-11-22 02:04:02
【问题描述】:
新手开发者学习 React。
我正在尝试在 React 中为博客文章创建一个投票功能,但是当我点击投票按钮时,我会同时投票所有的博客帖子卡片而不是单个卡片。
我该如何解决这个问题?我相信问题可能出在我设置 setState 的方式上?但我可能错了,正在寻求帮助。
提前致谢!
====
class Posts extends Component {
state= {
points: 0
}
componentDidMount() {
this.props.fetchPosts()
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.newPost) {
this.props.posts.unshift(nextProps.newPost);
}
}
handleClick = () => {
this.setState({points: this.state.points + 1})
}
render() {
const postItems = this.props.posts.map((post, index) => (
<div key={index} className="ui three stackable cards">
<div className="ui card">
<div className="content">
<div className="header">{post.title}</div>
<div className="meta"> {post.author}</div>
<div className="description">
<p>{post.body}</p>
</div>
</div>
<div className="extra content">
<i className="check icon"></i>
{this.state.points} Votes
</div>
<button className="ui button"
type="submit"
onClick={this.handleClick}>Add Point</button>
</div>
</div>
))
return (
<div>
<br />
<h2 className="ui header">
<i className="pencil alternate icon"></i>
<div className="content">
Blog Feed
<div className="sub header"><a href="/posts/new">Create New Post!</a></div>
</div>
</h2>
{postItems}
</div>
)
}
}
【问题讨论】:
-
您的帖子有唯一标识符吗?
标签: javascript reactjs react-redux state