React Hook 注意事项

2021-01-12  本文已影响0人  younglaker

useState

old:

class Exaple etends React.Componet {
    constructor(props){
        super(props)
        this.state = {
            count: 0
        }
    }
    
    
    return (
        <p> {this.state.count} </p>
        
        <button onClick={ ()=> this.setState({ count: this.state.count + 1 }) } > click </button>
    )

}

new

import React , {useState} from 'react'

function Example() {
    // 定义
    // 声明一个count的state变量,初始值为0;setCount()跟新state的函数
    // useState返回一个数组,array[0],array[1]
    const [count, setCount] = useState(0)
    
    return (
        // 读取
        //  this.state.count 改为 count
        <p> { count } </p>
        
        // 修改
        // this.state.count 改为 count
        // this.setState() 改为 setCount()
        <button onClick={ () => setCount(count + 1) } > click </button>
    )
}

其他例子

const [fruit, setFruit] = useState('apple')

useFruit('orange')

const [obj, setObj] = useState({ name: 'mike' })

//修改
//数组、对象需要赋值一个新的对象
setObj({name: 'jake'})

//新增
setObj({
    ...obj,
    age: 18
})

对象的useState设为[]会有问题

要设为null,在map的时候加?

const [projectData, setProjectData] = useState(null);

<Col span={24}>
    {projectData?.map((item: Project) => (
        <ProjectBox projectData={item} key={item.id} />
    ))}
 </Col>

useEffect

在函数组件中执行副作用操作


父调用子方法useRef

父:

 // 定义useRef
const creatFormRef = useRef(null);

// 调用子组件的方法
creatFormRef.current.restForm();

<CreateForm
  ref={creatFormRef}
/>

子 CreateForm:

import React, {useImperativeHandle, forwardRef } from 'react';

// 用useImperativeHandle暴露要调用的方法
 useImperativeHandle(ref, () => ({
    restForm: () => {
      ...
    },
}));

解决useEffect重复调用问题

https://juejin.cn/post/6844904117303934989
https://segmentfault.com/q/1010000017570341
https://www.jianshu.com/p/dcd6bc12dbee

如果你在useEffect中使用了useState则会导致无限循环。
为了处理这个问题,我们可以给useEffect传第二个参数。告诉react只有当这个参数的值发生改变时,才执行我们传的副作用函数(即第一个参数)。

当我们第二个参数传一个空数组[]时,相当于只在首次渲染的时候执行。

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    
  }, []);

useEffect 的 callback 函数中改变的 state 一定不能在该 useEffect 的依赖数组中。比如:useEffect(()=>{ setCount(count); }, [count]);依赖 count,callback 中又 setCount(count)。

WX20201223-192533.png

父组件调用子组件 --优雅方法一

  const onSubmitForm = async (data, clearForm) => {

    const res = await handeleApprove(data); //数据请求

    if (res.success) {
      clearForm()
    } else {
      message.error('提交失败');
      return false;
    }
  };

      <Approve
        onSubmitForm={onSubmitForm}
      />
const { onSubmitForm } = props;

<Button
type="primary"
onClick={() => {
  const res = onSubmitForm(
    data,
    clearForm() //传入清空的方法给父组件调用
  );

}}
>
提交
</Button>

父组件调用子组件 --优雅方法二

父组件调用,成功时返回值给子组件


  const onSubmitForm = async (data) => {

    const res = await handeleApprove(data); //数据请求

    if (res.success) {
      return true;
    } else {
      message.error('提交失败');
      return false;
    }
  };

子组件接收到请求成功的返回值来清空表单:

const { onSubmitForm } = props;

<Button
      type="primary"
      onClick={() => {
        const res = onSubmitForm(
          data,
        );
        if (res) {
          clearForm()
        }
上一篇 下一篇

猜你喜欢

热点阅读