React Hooks的用法及使用规则

React Hooks的用法及使用规则

Hooks是React v16.8加入的新特性。可以在class以外使用state和其他React特性。

1. State(状态) Hook

用法:

import {
          
    useState } from react;

function Example() {
          
   
  // 声明一个新的状态变量,我们将其称为 "count"
  const [count, setCount] = useState(0)  // 初始化数字
  const [str, setString] = useState("string") // 初始化字符串
  const [list, setLists] = useState([{
          
   val: li}]) //初始化数组
  
  const setHandle = () => {
          
   
    list[0].val = ning
    setTodos({
          
   
       ...list,
       list
    })
  }
  
  return (
     <>
      count: {
          
   count}
      str: {
          
   str}
      todos: {
          
   list[0].val}
      <br/>
      <button onClick={
          
   ()=>setCount(count+1)}>count handler</button>
      <button onClick={
          
   ()=>setHandle()}>lists handler</button>
    </>
  );
}
    useState两个参数,以数组的形式定义,通过数组解构赋给了声明的一个值引用,一个函数引用; useState返回第一个参数是 state 的属性; 第二个是用于修改这个属性的方法,传入参数为该属性的默认值; 设定的默认值仅仅是用在第一次render执行期间.,之后的更新就与这个默认值无关; state hook 不必使用setState更新, 也不必在 constructor 中绑定。
2. Effect(副作用) Hook
    useEffect在 React 的生命周期中相当于componentDidMount, componentDidUpdate, 和componentWillUnmount. 第二个参数不填代表任意 state 改变都将触发这个 effect
useEffect(() => {
          
   });
    只想执行一个 Effect 一次(挂载和卸载时),那么可以在 useEffect 的第二个参数中传入空数组;
useEffect(() => {
          
   }, []);
    希望 state 某个值或者某些值该变时,才执行这个 effect.比如,当count改变是执行useEffect
useEffect(() => {
          
   console.log(count)}, [count]);
    不要在 render 中调用 effect; 不要在 effect 中更新 state,否则将无限循环的执行;
const UseEffectPage = () => {
          
   
  const [count,setCount] = useState(0);

  useEffect(() => {
          
   
    setCount(count+1) // 不要在 render 中调用 effect
  }, [count])
  
  return (
    <>
      <div styles={
          
   styles.root}>{
          
   setCount(count+1)}</div> //不要在 effect 中更新 state
    </>
  )
}
Hooks规则
    Hooks只在顶层调用,不要在循环,条件判断或者嵌套函数中调用钩子。 只在React的函数组件(function Component)中调用Hooks,在类组件(class Component)中无法使用。 对于自定义Hooks,使用use开头命名。 eslint-plugin-react-hooks该插件可以规范hooks写法。 React 靠的是 Hook 调用的顺序来对应state和useState,所以一定要注意。
其他Hooks api未完待续。。。
经验分享 程序员 微信小程序 职场和发展