hook基础:useState、useEffect;
useState
用与声明组件状态与修改状态的方法,例:
const [cards, setCards] = useState('current cards');
const [profile, setProfile] = useState({name: 'liaoxinyu', status: 'writing'});
1.cards为组件状态,初始值为:current cards
2.setCards为修改cards数据的方法,如:setCards(‘new cards’),cards将更新为’new cards’
3.申明多个状态即多写几个useState
useEffect
在函数组件中执行代码,比如网络请求、修改组件状态等,例:
import React, { useEffect, useState } from 'react';
const Example = () => {
const [count, setCount] = useState(0)
const [title, setTitle] = useState('original title')
const [profile, setProfile] = useState({name: 'liaoxinyu', status: 'writing'});
useEffect(() => {
setTitle('new title...' + count)
// 将在组件创建时执行某些代码
// 这里修改了标题
return () => {
setTitle('original title')
}
// useEffect中的return,会在组件销毁时执行,用于销毁某些副作用代码
// 比如将数据还原
}, [count]);
// 这里设置了 [count] ,即当count变更后,会自动执行 setTitle('new title...' + count)
// 如果设置 [] 空数组,这条useEffect将只执行一次
return (
<div>
<p>{ title }</p>
<p>current count: { count }</p>
<p>author: { profile.name }</p>
<button onClick={() => setCount(count + 1)}>modify count</button>
</div>
)
// 渲染 title、count
// 点击button按钮,调用setCount,将count加1
}