LoginSignup
34
24

More than 5 years have passed since last update.

ReactのsetStateで配列の一部を変更する

Last updated at Posted at 2018-03-07

備忘録

Reactの勉強をはじめて2時間詰まったところ↓
reactのstateに配列を設定した時、インデックスを利用して一部を変更したい。

解決策

スライスで配列をコピーしてからコピーの中身を変更して、それをsetStateする

constructor(props) {
        super(props);
        this.state = {
            humans: ["", "", ""]
        }
    }

    change(i) {
        const humans_copy = this.state.humans.slice();
        humans_copy[i] = "変更"
        this.setState({humans: humans_copy})
    }
}

結局チュートリアルでした。

34
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
24