0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】 配列 に対して UseState を使用する

Last updated at Posted at 2021-12-07

■前提
Reactの実行環境がある。
App.jsでsample.jsをimport及び呼びだすコードがある。

■以下前提のコード

sample.js
import React, {useState} from 'react'
const sample= () => {
}
export default sample

■以下state(sampleobject)とstateを更新するための関数(setsampleobject)を定義する。
 また、値を追加していく変数(newsampleobject)も定義する。

sample.js
import React, {useState} from 'react'

const sample= () => {
    const [sampleobject, setsampleobject] = useState([])
    const newsampleobject = () => {
        setsampleobject([...sampleobject,{
            id: sampleobject.length,
            name: "Hello"
        }])
    }
    return (
        <>
        </>
    )
}

■以下ボタンと配列の内容を展開する処理を追加。

sample.js
import React, {useState} from 'react'

const sample= () => {
    // 以下オブジェクト(sampleobject, setsampleobject)を定義する。
    const [sampleobject, setsampleobject] = useState([])
    const newsampleobject = () => {
        setsampleobject([...sampleobject,{
            id: sampleobject.length,
            name: "Hello"
        }])
    }
    return (
        <div>
            <button onClick={newsampleobject}>Add New sampleobject</button>
            <ul>
                {sampleobject.map(sampleobject =>(
                    <li key={sampleobject.id}>{sampleobject.name} id: {sampleobject.id}</li>
                ))}
            </ul>

        </div>
    )
}

■結果
ボタンを押すと、Hello id: 連番 が表示される。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?