react_hooks笔记
邵预鸿 Lv5

useState

1
2
3
4
5
6
7
8
9
10
11
12
13
function AboutHook() {
const [count, setCount] = useState(0);
const [show, setShow] = useState(true)
return (<div>
<h2>this is abouthook.js</h2>
<button onClick={() => setShow(!show)}>显示/隐藏子组件</button>
<p>
<button onClick={() => setCount(count - 1)}>-</button>
<span>{count}</span>
<button onClick={() => setCount(count + 1)}>+</button>
</p>
</div>);
}

注意,在useEffect使用定时器设置useState的值时,请使用回调函数的形式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const [count,setCount] = useState(1);
const [now,setNow]= useState();
const recored = useRef();
let timer = null;
useEffect(() => {
addCount();
setTime();
return () => {
console.log('销毁了');
clearInterval(timer);
}
}, []);
const addCount = ()=>{
timer = setInterval(()=>{
setCount(count=>count+1);
},1000)
}

createContext()

  • 使用公共文件将实例导出 export default const context = createContext()
  • 将需要暴露的数据通过**<C.provider value={值}></C.provider>**
  • 子孙组件里面中使用useContext实例,const C = useContext(导出的实例)。C里面包含传入的数据

useContext()

针对function函数式组件的接收值 ,类式组件采用 static contextType = ThemeContext; tihs.context中就是provider传入的值

useEffect

  • 一个function中可以存在多个useEffect

  • ```js
    useEffect(()=>{

        console.log('props.count更新时触发 ');
     
    },[props.count]); //componentDidMount + count变化时的componentDidUpdate
    
    1
    2
    3
    4
    5
    6
    7

    * ```js
    useEffect(()=>{
    return ()=>{
    console.log('销毁了')
    }
    },[]) //componentDidMount +componentUnDidMount
  • useEffect(()=>{
        ....
        return ()=>{
            console.log('销毁了')
        }
    },[count]) //componentDidMount +componentDidUpdate + componentUnDidMount
    首次+count更新,更新的同时会触发销毁
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21

    #### useReducer实现reducer状态管理

    ```js
    function Test() {
    const defaultState = {
    color: 'red'
    }
    const [store, dispatch] = useReducer((state, action) => {
    if (action.type === 'changeColor') {
    return { ...state, color: action.payload.color }
    }
    return state;
    },defaultState);
    return (<div>
    <createContext2.Provider value={ {store:store,dispatch} }>
    <BtnGroup></BtnGroup>
    <Message></Message>
    </createContext2.Provider>
    </div>)
    }

useMemo

useMemo 主要用于性能优化,在hooks中数据更新会使页面重新渲染,如果 页面有调用 的函数,那么相关函数将重新计算并调用 ,useMeno主要用于解决多于调用 的问题

1
2
3
4
5
6
7
8
9
 const sum =useMemo(()=>{
var sum =0;
for(var i=0;i<1000;i++){
sum+=i;
}
console.log("sum触发")
return sum;
},[age])
//调用时{sum} 不再是函数

由于useMemo会执行函数,并返回函数 的结果 ,useMemo可以替换useCallBack

1
2
3
useMemo(()=>val=>setText(val),[val])

useCallBack((val)=>{setText(val)},[val])

useCallBack

useCallBack会缓存函数,并不会执行,而是返回这个函数

useMemo会执行函数。并返回函数的结果

useRef

useRef可以用于存储变量或者 dom元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { useRef,useState } from 'react';
export default function Test(props){
const [text,setText] = useState('');
const v = useRef(''); //记录值
const dom = useRef(null); //记录dom
const submit = ()=>{
console.log('提交表单');
console.log(text);
console.log('v的值:',v.current);
console.log(dom);
}
return (<div>
<hr/>
<h3>02_useRef.jsx</h3>
<input value={text} onChange={e=>{setText(e.target.value); v.current = e.target.value}}></input><button ref={dom} onClick={()=>submit()}>提交</button>
<div>
<input type='radio' value="1" checked={text ==='1'} onChange={(e)=>{setText(e.target.value)}} name="tag"/>标签1
<input type='radio' value="2" checked={text ==='2'} onChange={(e)=>{setText(e.target.value)}} name="tag"/>标签2
<input type='radio' value="3" checked={text ==='3'} onChange={(e)=>{setText(e.target.value)}} name="tag"/>标签3
<input type='radio' value="4" checked={text ==='4'} onChange={(e)=>{setText(e.target.value)}} name="tag"/>标签4
</div>
</div>)
}

自定义hooks 与vue雷同,把hooks提出去

以以下逻辑为例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import '@assets/index.css';
import { useState,useEffect } from 'react';
export default function InitHooks(props){
const [list,setList] = useState([]);
useEffect(() => {

setTimeout(()=>{
const arr = [...Array(10).keys()];
setList(arr);
},2000);
}, [])
return (<div>
<h3>this is inithooks.jsx</h3>
<ul>
{list.map((item,index)=>( <li key={index}>{item} <button>删除</button></li>))}

</ul>
{list.length ==0 && <p>请求中</p>}
</div>)
}

效果图如下

http://server.yuhongshao.cn/static/yuhongshao/20220530160528.png

使用自定义hooks后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import '@assets/index.css';
import { useState,useEffect } from 'react';
function useCreateList(){
const [list,setList] = useState([]);
useEffect(() => {

setTimeout(()=>{
const arr = [...Array(10).keys()];
setList(arr);
},2000);
}, []);
return {
list,
setList
}
}

function useDelItem(){
const delItem = ({idx,list,setList})=>{
console.log(idx);
const arr = list.filter((item,index)=>index!==idx);
setList(arr);

}
return delItem;

}

export default function InitHooks(props){

const {list,setList} = useCreateList();
const delItem2 = useDelItem();
return (<div>
<h3>this is inithooks.jsx</h3>
<ul>
{list.map((item,index)=>( <li key={index}>{item} <button onClick={()=>delItem2({idx:index,list,setList})}>删除</button></li>))}

</ul>
{list.length ==0 && <p>请求中</p>}
</div>)
}
  • 本文标题:react_hooks笔记
  • 本文作者:邵预鸿
  • 创建时间:2021-08-30 10:23:51
  • 本文链接:/images/logo.jpg2021/08/30/react-hooks笔记/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!