我正在创建一个关于电影的应用程序,在其中我尝试为每部电影评分。我现在面临的问题是我无法分别评价每部电影。当我给一部电影评分时,所有电影都获得相同的评分。关于如何使其工作的任何想法?我如何分别评价每个项目?
class App extends React.Component {
constructor() {
super();
this.state = {
rating: 0
};
}
onStarClick(nextValue) {
this.setState({rating: nextValue
});
}
render() {
const { rating } = this.state;
return (
<div>
<h2>Top 10 movies</h2>
{movies.map(c => (
<div>
<p key={c.name}>
{c.name}
</p>
<StarRatingComponent
name="rate1"
starCount={10}
value={rating}
onStarClick={this.onStarClick.bind(this)}
/>
</div>
))}
</div>
);
}
}
答案 0 :(得分:2)
您需要一部电影来单独而不是一个整数来对映射进行评级。保留为数组
class App extends React.Component {
constructor() {
super();
this.state = {
rating: new Array(movies.length).fill(0)
};
}
onStarClick(index, nextValue) {
this.setState(prevState => ({rating: [
...prevState.rating.slice(0, index),
nextValue,
...prevState.rating.slice(index + 1)
]
}));
}
render() {
const { rating } = this.state;
return (
<div>
<h2>Top 10 movies</h2>
{movies.map((c, index) => (
<div>
<p key={c.name}>
{c.name}
</p>
<StarRatingComponent
name="rate1"
starCount={10}
value={rating[index]}
onStarClick={this.onStarClick.bind(this, index)}
/>
</div>
))}
</div>
);
}
}