zoukankan      html  css  js  c++  java
  • react-hooks 官方文档笔记

    1、useState 

    import { useState } from 'react';

    function Example () {

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

      return (<div>

          <span>{count}</span>

          <button onClick={ () => { setCount(count+1) } }>增加次数</button>

      </div>);

    }


    2、useEffect 

    Effects without cleanup 

    import { useEffect } from 'react;

    useEffect(() => {

      document.title = 'try to underStand what is effects';

    });

    What does useEffect do?

    By using this Hook, you tell React that your component needs to do something after render.

    React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates.

    In this effect, we set the document title, but we could also perform data fetching or call some other imperative API.

    // Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.

    // useEffect is similar to componentDidMount and componentDidUpdate

    Why is useEffect called inside a component? 

    Placing useEffect inside the component lets us access the count state variable (or any props) right from the effect.

    We don’t need a special API to read it — it’s already in the function scope.

    Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a solution.

    Does useEffect run after every render? 

    Yes!By default, it runs both after the first render andafter every update.

    Instead of thinking in terms of “mounting” and “updating”,

    you might find it easier to think that effects happen “after render”.

    React guarantees the DOM has been updated by the time it runs the effects.

    Experienced JavaScript developers might notice thatthe function passed to useEffect is going to be different on every render.

    This is intentional. In fact, this is what lets us read the count value from inside the effect without worrying about it getting stale.

    Every time we re-render, we schedule a different effect, replacing the previous one.

    In a way, this makes the effects behave more like a part of the render result — each effect “belongs” to a particular render. 

    Effects with cleanup 

    In a React class, you would typically set up a subscription in componentDidMount, and clean it up in componentWillUnmount

    Notice how componentDidMount and componentWillUnmount need to mirror each other.

    Lifecycle methods force us to split this logic even though conceptually code in both of them is related to the same effect.

    useEffect(() => {

      function setFriendStatus (status) {

      }

      chatApi.subscibeToFriendStatus(id,setFriendStatus);

      return function cleanUp () {

        chatApi.unSubscibeFromFriendStatus(id,setFriendStatus);

      } // We don’t have to return a named function from the effect. We called it cleanup here to clarify its purpose, but you could return an arrow function or call it something different.

     });

    You might be thinking that we’d need a separate effect to perform the cleanup.

    But code for adding and removing a subscription is so tightly related that useEffect is designed to keep it together.

    If your effect returns a function, React will run it when it is time to clean up:

    Why did we return a function from our effect? 

    This is the optional cleanup mechanism for effects.

    Every effect may return a function that cleans up after it.

    This lets us keep the logic for adding and removing subscriptions close to each other.

    They’re part of the same effect!

    When exactly does React clean up an effect? 

    React performs the cleanup when the component unmounts.

    However, as we learned earlier, effects run for every render and not just once.

    This is why React also cleans up effects from the previous render before running the effects next time. 

    Tip: Optimizing Performance by Skipping Effects

    useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); // Only re-run the effect if count changes


    3、Rules of Hooks

    Only Call Hooks at the Top Level

    Don’t call Hooks inside loops, conditions, or nested functions.

     Instead, always use Hooks at the top level of your React function.

    By following this rule, you ensure that Hooks are called in the same order each time a component renders.

    That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.  

    Only Call Hooks from React Functions

    Don’t call Hooks from regular JavaScript functions. Instead, you can:

    • ✅ Call Hooks from React function components.
    • ✅ Call Hooks from custom Hooks 
  • 相关阅读:
    Git 使用规范流程
    关于Python的super用法研究
    python中try except处理程序异常的三种常用方法
    break 和 continue 语句, 以及循环中的 else 子句
    杂记(python)
    Request和Response
    MVC项目开发步骤
    Web中单元测试步骤
    JSP中的细节
    WEB中地址的写法
  • 原文地址:https://www.cnblogs.com/cheeseCatMiao/p/10677470.html
Copyright © 2011-2022 走看看