reactHooks 回顾useState和Context详解 useState 使用注意事项
- useState 不可局部更新
- useState 地址要变
- setN 优先使用函数的形式
// 只是改变age,但是name也被清除了
let App=()=>{
const [u,Setn]=useState({name:'zhangsan',age:18})
useupdate(()=>{
console.log('u变化了')
},u)
const add = () => {
Setn({age:19})
//19
}
return (
<>
<div>
{'测试update'}
<div>{u.name}</div>
<div>{u.age}</div>
</div>
<button onClick={add}>change</button>
</>
)
}
const add = () => {
u.name="lihua"
Setn(u)
// 这样会以为还是原来的对象,所以lihua 并没有生效
}
useReducer 使用注意事项
const initialState={
n:1
}
// 对数据的一些操作
const reducer=(state,actions)=>{
// state 操作原有数据 actions操作
if(actions.type==="add"){
return {n:state.n+actions.number}
}
else if(actions.type==="mult"){
return {n:state.n*2}
}
else {
throw new error('no type')
}
}
let App=()=>{
// 使用reducer
// state 就是initstate对象,dispatch操作(因为是调用actions的方法)所以用dispatch
const [state,dispatch] = useReducer(reducer,initialState)
const add = () => {
dispatch({type:'add',number:5})
}
return (
<>
<div>
{'测试update'}
<div>{state.n}</div>
<div></div>
</div>
<button onClick={add}>change</button>
</>
)
}
什么时候使用useReducer 什么时候使用useState 如果是对多个变量可以集合在一起{name,age}的数据操作 就可以使用useReducer
Context使用注意事项 不是响应式更新数据,而是逐级往下通知 更新数据重新渲染,这和vue3响应式不太一样
import React, { useState, createContext, useContext } from 'react';
import './App.css';
// 第一步 全局声明一个上下文 可以理解为是一个局部的全局变量,作用范围是C.provider
const C=createContext(null)
let App=()=>{
const [person,setN]=useState({name:'李华',age:18})
// 第二步 C.provider
return (
<>
<C.Provider value={{person,setN}}>
<div>
{'测试update'}
<Father name={person.name}></Father>
</div>
</C.Provider>
</>
)
}
let Father= (props)=>{
return (
<>
<Son></Son>
<p>爸爸 <span>{props.name}</span></p>
</>
)
}
let Son= (props)=>{
// 第三步 person 变量名要和provide.value中的变量名保持一致
const {person,setN}=useContext(C)
console.log(person)
return (
<>
<p>儿子 <span>我得到的年龄{person.age}</span></p>
</>
)
}
export default App