7
3

More than 3 years have passed since last update.

ネスト(nest)した State の要素を setState で変更する(React)

Last updated at Posted at 2019-10-08

解決する課題

Reactで値を保持する箇所といえばstate

setStateメソッドで、stateの値を変更できますが、
ネストされた要素は直接 setStateで変更できません (React 16.2現在)

しかしながらstateでネストした要素を変更することがよくあります。

思ったより以上に情報が少ない為、

単純な解決方法を1つを記事にします

Typescriptを利用します。
Javascriptよりもコードはわかりやすく見えると思います。


結論 (コード用意しました)

どういうコードなの?

人間(humanDetail) の詳細に 名前、年齢、性別のプロパティを設けます

今回は tom さんの年齢を 18 ⇒20に変更するというコードです。


//PlayGroundからコピペしたから、importは割と適当だよ
//importは適宜変更してね

import * as React from "react";
import { render } from "react-dom";
import { Button } from "antd";
import "antd/dist/antd.css";



interface humenDetail {
    name: string;
    age: number;
    sex: boolean; // true:men false:women
}

interface Props {}

interface State {
    human: humenDetail | null;
}

class App extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props);

        this.state = {
            human: { name: "tom", age: 18, sex: true }
        };
    }

    nestedStateChange = () => {
        const item = this.state.human;
        if (item !== null) {
            item.age = 20; //ここに変更する値
        }

        this.setState({
            human: item
        });
        console.log(this.state.human);
    };

    render() {
        return (
            <div>
                <Button onClick={this.nestedStateChange}>
                    ここを押すと、値が18⇒20に変わるよ
                </Button>
                <div>{this.state.human.age}</div>
            </div>
        );
    }
}

render(<App />, document.getElementById("root"));


nestedStateChangeメソッドで ネストする前のプロパティを itemとして指定して、itemのプロパティに値を入れて
item を setStateするよーっていうオーソドックスなやり方です。

7
3
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
7
3