React开发学习02-React 与 Hook 应用(React数据获取与渲染)

useEffect, useState

由于没详细了解过目前仅仅是会用

首先引入两个组件

import { useEffect, useState } from "react";

填写需要的参数以及设置参数变化时的函数:

  const [param, setParam] = useState({
    name: "",
    personId: "",
  });

使用更新函数:
第一个参数为更改的属性,第二个为更改的值

            setParam({
              ...param.name,
              name: evt.target.value,
            })

useEffect更像vue中的computed监听改变后对都没进行处理或请求参数:

  useEffect(() => {
    fetch("").then(async (response) => {
      if (response.ok) {
        setList(await response.json);
      }
    });
  }, [param]);

react 状态提升

父传子:在函数参数内解构参数

      <SearchPanel users={users} param={param} setParam = {setParam}/>
export const List = ({list,users})=>{
    console.log(list);
    return <table> </table>
}

动态渲染: 与vue相同避免index做key值

export const List = ({list,users})=>{
    console.log(list);
    return <table>
        <thead>
            <tr>
                <th>名称</th>
                <th>负责人</th>
            </tr>
        </thead>
        <tbody>
    {
        list.map(project=>
            <tr key={project.id}>
                <td>{project.name}</td>
                <td  >{users.find(user=>
                    user.id === project.personId
                )?.name || '未知'}</td>
            </tr>
            )
    }
        </tbody>
    </table>
}

**qs:**该插件可以讲参数对象转换为键值对形式

    useEffect(() => {
      fetch(`${apiUrl}/projects?${qs.stringify(cleanObject(param))}`).then(async (response) => {
        if (response.ok) {
          setList(await response.json());
        }
      });
    }, [param]);

使用 Custom Hook提取并复用组件代码

定义:

//一定要用use开头
export const useMount = (callback)=>{
    useEffect(()=>{
        callback()
    },[ ])
}

使用:避免重复实现

    useMount(() => {
      fetch(`${apiUrl}/users`).then(async (response) => {
        if (response.ok) {
            setUsers(await response.json());
        }
      });
    });

用costume Hook实现:

export const useDebounce = (value,delay) => {
    console.log(value);
    //把value变成监听value
  const [debouncedValue, setDebouncedValue] = useState(value)

  useEffect(() => {
    // 每次在value变化以后,设置一个定时器
    const timeout = setTimeout(() => setDebouncedValue(value), delay);
    // 每次在上一个useEffect处理完以后再运行
    return () => clearTimeout(timeout);
  }, [value, delay]);

  return debouncedValue;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值