簡體   English   中英

使用setState()時,如何在React組件中單獨更新數組索引的狀態而又不影響整個數組本身?

[英]How can I update the state of an array index individually in a React component without effecting the whole array itself when using setState()?

我正在重新審視一個我曾問過的老問題,並以不同的方式對待它。 目前,我想更新分數數組。 當前發生的情況是當onClick函數運行時,它會刪除整個數組。 我如何只更新我要指定的數組索引?

class App extends React.Component {
    constructor(props) {
        super(props);
        this.scoreFive = this.scoreFive.bind(this);
        this.state = { 
            score: [10, 20]
         }
    }
    scoreFive(key) {
        this.setState((prevState) => {
            return {
                score: [
                    prevState.score[key] + 5
                ]
            }
        })
        console.log(key)
    }


    render() { 
        return ( 
            <div>
                <h1>Dominoes</h1>
                <Player key={1} name="micah" score={this.state.score[0]} scoreFive={() => this.scoreFive(0)} />
                <Player key={2} name="kyndra" score={this.state.score[1]} scoreFive={() => this.scoreFive(1)} />
            </div>
         );
    }
}
const newArray = this.state.score.map(element => element + 5);

然后執行:

this.setState({score: newArray});

map函數使用您的條件返回一個新數組。

有什么問題讓我知道:)

您必須從先前的狀態獲取數組,對其進行克隆,修改某些索引,然后使用該狀態更新狀態:

 score: prevState.score.map((value, index) => index === key ? value + 5 : value)

如果您經常這樣做,那么它會重復很多,您也可以將其抽象為一個助手:

  const lens = (key, cb) => obj => ({ ...obj, [key]: cb(obj[key]) });
  const index = (index, cb) => array => array.map((v, i) => i === index ? cb(v) : v);

可用作:

  this.setState(lens("score", index(key, it => it + 5)));

嘗試:

   scoreFive(index) {
        this.setState((prevState) => {
            const score = prevState.score; // reference the array
            score[index] + 5; // modify the specific index

            return {
                score: score
            };            
        })
        console.log(key)
    }

更新分數並設置狀態。

   scoreFive(key) {
        let {score} = this.state;
        score[key] += 5;
        this.setState({score});
    }

編輯----------------------

因此,經過研究和一些否定標記后,我發現我做錯了,並且按照不改變數據的功效對狀態進行了改變

所以這是更新的實現

   scoreFive(key) {
        this.setState({score: this.state.score.map((data, index) => index === key ? data + 5 : data) });
    }

謝謝你的協助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM