Sep 30, 2019
ReactのStateの初期化について
↓ 一般的な初期化方法
import React, { useState } from 'react'
const Sample: React.FC = () => {
const [ count, setCount ] = useState(0)
const decreaseCount = () => {
setCount(count - 1)
}
const increaseCount = () => {
setCount(count + 1)
}
return (
<div>
<button onClick={decreaseCount}> - </button>
<span> {count} </span>
<button onClick={increaseCount}> + </button>
</div>
)
}
export default Sample
↓ のようにも書ける
import React, { useState } from 'react'
const countInitial = () => {
return 0
}
const Todo: React.FC = () => {
const [ todos, setTodos ] = useState(() => countInitial())
const decreaseCount = () => {
setCount(count - 1)
}
const increaseCount = () => {
setCount(count + 1)
}
return (
<div>
<button onClick={decreaseCount}> - </button>
<span> {count} </span>
<button onClick={increaseCount}> + </button>
</div>
)
}