我已经看过了react v16中介绍的钩子.7.0.

https://reactjs.org/docs/hooks-intro.html

所以我对钩子的理解是,我们可以在函数组件中使用状态,而不用在react中编写类组件.这真是一个惊人的功能.

但我并没有弄清楚在功能组件中使用钩子.

   import { useState } from 'react';

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

    return (
      <div>
        <p>You clicked {count} times</p>
        <button onClick={() => setCount(count + 1)}>
         Click me
        </button>
      </div>
   );
  }

如果使用钩子,如何在上述功能组件中使用生命周期方法?

推荐答案

以下是最常见的生命周期示例:

组件安装

将空数组作为第二个参数传递给useEffect(),以便仅在装载时运行回调.

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, []); // Pass an empty array to run only callback on mount only.

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

componentDidUpdate (loose)

通过将单个参数传递到useEffect,它将在每次渲染后运行.这是一个松散的类似功能,因为这里有一个细微的区别,componentDidUpdate不会在第一次渲染后运行,但是这个钩子版本会在每次渲染后运行.

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }); // No second argument, so run after every render.

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

componentDidUpdate (strict)

本例与上述示例的不同之处在于,这里的回调不会在初始渲染时运行,严格模拟componentDidUpdate的语义.这answer is by Tholle美元,全归功于他.

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

  const firstUpdate = useRef(true);
  useLayoutEffect(() => {
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }

    console.log('componentDidUpdate');
  });

  return (
    <div>
      <p>componentDidUpdate: {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

组件将卸载

useEffect的callback参数中返回一个回调,它将在卸载之前被调用.

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

  useEffect(() => {
    // Return a callback in useEffect and it will be called before unmounting.
    return () => {
      console.log('组件将卸载!');
    };
  }, []);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

应该更新组件吗

您已经可以使用React.PureComponentReact.memo在组件级别实现这一点.为了防止子组件重新招标,此示例取自React docs:

function Parent({ a, b }) {
  // Only re-rendered if `a` changes:
  const child1 = useMemo(() => <Child1 a={a} />, [a]);
  // Only re-rendered if `b` changes:
  const child2 = useMemo(() => <Child2 b={b} />, [b]);
  return (
    <>
      {child1}
      {child2}
    </>
  )
}

getDerivedStateFromProps

再一次,从React docs人中摘取

function ScrollView({row}) {
  let [isScrollingDown, setIsScrollingDown] = useState(false);
  let [prevRow, setPrevRow] = useState(null);

  if (row !== prevRow) {
    // Row changed since last render. Update isScrollingDown.
    setIsScrollingDown(prevRow !== null && row > prevRow);
    setPrevRow(row);
  }

  return `Scrolling down: ${isScrollingDown}`;
}

更新前获取快照

目前还没有类似的钩子.

组件捕获

目前还没有类似的钩子.

React-native相关问答推荐

错误:HostBody::get for prop NativeUnimoduleProxy中出现异常- Android虚拟设备(AVD)使用Expo测试React Native App时崩溃

领带麦克风在Reaction-Native-Incall-Manager中不工作

React Native Axios 通过数组的键过滤

无法在 M1 zsh 上运行 adb segmentation fault adb

如何在 React / React Native 中使用 Emscripten 编译的 JavaScript

react native :navigationOptions 中的标题样式不起作用

Android Studio 为构建设置 node 目录(Cause: error=2, No such file or directory)

在 React 中使用 Lodash debounce 来防止在用户输入时请求数据

混合 JavaScript 移动开发 - Apache Cordova vs Capacitor with Ionic vs NativeScript vs React Native

react-native android中出现此问题Cannot convert argument of type class org.json.JSONArray的原因是什么?

Fragment片段内的react-native

React native Redux - 对象不是构造函数(判断'new ctor(props context)')

React Native Expo StackNavigator 重叠通知栏

React Native:当我从 XCode 运行应用程序时看不到 console.logs

使用 Jest 的 react-navigation 测试组件

react-native 中的倒数计时器

如何在 react native 中将数组保存在异步存储中?

我将如何根据百分比为按钮的宽度设置动画,并且它的背景 colored颜色 也是如此?

React Native - 如何从推送通知中打开路由

在 React Native 中向组件传递参数