React Hooks 学习笔记

1.userContext的使用

使用场景, 组件之间需要共享状态

父组件

import React, { useState } from 'react';
import Child from './child.js'
import Child2 from './child2.js'
import CountContext from './common'

function Example(){
    const [count , setCount ] = useState(666)
    return(
        <div>
            <div>
                <p>you click {count -666 } times</p>
                <button onClick={()=>{setCount(count+1)}}>click me</button>
                <CountContext.Provider value ={count}>
                    <Child/>
                    <Child2/>
                </CountContext.Provider>
            </div>
        </div>
    )
}

export default Example

子组件1

import React, { useContext } from 'react';
import CountContext from './common'

function Child(){
    let count = useContext(CountContext)
    return(<h2>儿子1:{count}</h2>)
}

export default Child

子组件2

import React, { useContext } from 'react';
import CountContext from './common'

function Child(){
    let count = useContext(CountContext)
    return(<h2>儿子2:{count}</h2>)
}

export default Child

公共组件

import  {createContext } from 'react';
const CountContext = createContext(80);
export default CountContext

效果

二、父子传值

父组件

  <ConfirmModal
     attribution={attribution}
     location={props.location}
     func={confirmClose}
     onFinish={() => {
       confirmClose();
       setFinish(true);
     }}
     agent_id={
       props.location.query.agent_id
        ? props.location.query.agent_id
       : ''
      }
     values={values}
     number={number}
     products={screen.products}
 />

子组件

export default ({location, values, products, number = { price: 0 }, func, onFinish, attribution, agent_id}) => {

//触发父组件函数

//写入默认值 相当于 this.setState
useState(() => {
//写入邮箱默认值
if (values.email === undefined || values.email === '') {
values.email = values.select_number + '@189.cn';
}
//写入宽带安装地址默认值
if (values.broadband_address && values.broadband_address.length > 0) {
values.broadband_address = attribution + values.broadband_address;
}
//写入承保地址默认值
if (
values.gift_address === undefined ||
(values.gift_address === '' &&
product.gifts.find((item) => item.id === values.gift_id)
.need_address)
) {
values.gift_address = values.detail_address;
}
});
 
onFinish && onFinish();  //可传值
}

3.卸载时清除定时器

 const time = React.useRef(null)
useEffect(() => {
        return() => {
       clearIntervel(time.current)
      } 
});

4.根据某个值的修改 触发其他函数

//只要value值变化了 , 就会触发getList()函数
useEffect(() => { getList() }, [value]);

遇到的BUG

1.使用create-react-app 创建应用的时候

指令create-react-app 不存在 ,使用npx create-react-app 即可

2.使用antd-design 组件Button时 报错

 经检查,发现是antd版本没跟上react更新导致

解决方法 降低react和react-dom 版本为16.12.0 ,  antd版本降为4.4.2

原文地址:https://www.cnblogs.com/it-Ren/p/13451601.html