0
我正在嘗試爲數組中的每個元素實現一個計數器並將它們顯示在屏幕上。我有一個數組,我想爲每個元素顯示以下內容:汽車名稱,喜歡,增加按鈕和減少按鈕。當我試圖增加和減少喜歡時,所有的元素都會以同樣的方式增加和減少。我如何讓喜歡獨立於彼此而不共享喜歡?例如,當我喜歡一輛汽車時,我只希望那輛汽車增加likes
的數量。有人可以幫助我解決這個問題嗎?這是我現在的代碼:React.js中每個項目的計數器
import React, {Component} from 'react';
class Cars extends Component {
constructor(props) {
super(props);
this.state = {
likes: 0
};
this.incFav = this.incFav.bind(this);
this.decFav = this.decFav.bind(this);
}
incFav(e) {
this.setState({likes: this.state.likes + 1});
}
decFav(e) {
this.setState({likes: this.state.likes - 1});
}
render() {
//Passed this.props.cars from another component. It is an array of cars.
const { cars } = this.props;
return (
<div>
{cars.map((car, key) => {
<li key={car}>
{car}
{this.state.likes}
<button onClick={this.incFav}>+</button>
<button onClick={this.decFav}>-</button>
</li>
})}
</div>
);
}
}
export default Cars;
那有道理。我注意到在你的'incFav()'和'decFav()'方法中,你使用了一個回調函數而不是'likes:this.state.likes + 1'和'likes:this.state.likes - 1「。使用回調和我的初始方法有什麼區別? – prindod
現在,如果我的未來狀態依賴於舊狀態,我將其作爲一種習慣使用,這種方法保證'prevState'是最新的,並且我不會得到舊狀態(這可能會導致某些場景中奇怪的狀態更新) 。在你的具體情況下,你應該沒問題,但我建議養成更新狀態的習慣,如圖所示,如果新狀態取決於最新的狀態。 – G4bri3l
https://facebook.github.io/react/docs/react-component.html#setstate – G4bri3l