LoginSignup
0
0

More than 3 years have passed since last update.

ReactでJSONデータをmap型で扱うときの注意点

Posted at

APIからJSONを取得


    componentWillMount(){
        console.log("getpod")
        const request = axios.create({
            baseURL: "http://127.0.0.1:8080",
            method: "GET"
        })

        request.get("/getpods")
            .then(request => {
                // console.log(request.data)
                this.setState({
                    pods: request.data.items
                })
                console.log(this.state.pods)
            })
    }

JSONの要素を取り出す


                    <div>
                        <ul>
                            {this.state.pods.map((pod) => {
                                return <li>{pod.metadata.name}  {pod.status.phase}</li>;
                            })}
                        </ul>
                    </div>

取得されたJSONデータ

image.png

注意ポイント

  • reqest.data とすると、一番はじめの要素がルートというか頭の部分になるのだけど、renderするときにpod.items.metadata.nameみたいなことをやってもエラーになった
  • request.data.itemsとすると、一番はじめの要素がmap形式になるようで、renderするときにその次の要素から指定すればエラーはでなかった
  • つまるところ、stateにいれる値はmap型の階層まで定義してあげて、その部分から下の要素を普通に指定してあげればいいみたい
    • そのため、取得したJSONデータの中に複数の層にまたがって必要なデータがある場合、stateを複数定義してあげてmap形式の階層で定義してあげればよいみたい
  • いまいちなんでかはわからない
0
0
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
0
0