import React,{useState} from ‘react‘
export default function ComplexHookState() {
const [friends, setFriends] = useState([‘李雷‘,‘科比‘])
const [students, setStudents] = useState([
{ id:110, name:‘Eric‘, age:28 },
{ id:111, name:‘kebo‘, age:22 },
{ id:112, name:‘lily‘, age:25 }
])
function incrementAgeWithIndex(index){
const newStudents = [...students]
newStudents[index].age += 1
setStudents(newStudents)
}
return (
<div>
<h2>好友列表</h2>
<ul>
{ friends.map((item,index)=>{ return <li key={index}>{item}</li> }) }
<button onClick={e => setFriends([...friends,‘tom‘])}>添加朋友</button>
</ul>
<h2>学生列表</h2>
<ul>
{ students.map((item,index)=>{
return ( <li key={index}> <span>名字:{item.name} 年龄:{item.age}</span>
<button onClick={e=> incrementAgeWithIndex(index)}>age+1</button> </li> )
}) }
</ul>
</div>
)
}
import React ,{useState} from ‘react‘
export default function CounterHock() {
const arr = useState(0);
console.log(arr);
const state = arr[0];
const setState = arr[1];
return (
<div>
<h2>当前计数: {state}</h2>
<button onClick={e=> setState(state + 1 )} > +1 </button>
<button onClick={e=> setState(state - 1 )} > -1 </button>
</div>
)
}