首页 > 其他分享 >React Hooks 入门教程【阮一峰】

React Hooks 入门教程【阮一峰】

时间:2024-05-08 10:44:06浏览次数:23  
标签:const Hooks React 一峰 钩子 组件 return useEffect

组件类的缺点

  • React 的核心是组件。早前版本,组件的标准写法是类。
    // 一个简单的组件类
    import React, { Component } from "react";
    
    export default class Button extends Component {
      constructor() {
        super();
        this.state = { buttonText: "Click me, please" };
        this.handleClick = this.handleClick.bind(this);
      }
      handleClick() {
        this.setState(() => {
          return { buttonText: "Thanks, been clicked!" };
        });
      }
      render() {
        const { buttonText } = this.state;
        return <button onClick={this.handleClick}>{buttonText}</button>;
      }
    }
  • 组件类的缺点:
    • 大型组件很难拆分和重构,也很难测试。
    • 业务逻辑分散在组件的各个方法之中,导致重复逻辑或关联逻辑。
    • 组件类引入了复杂的编程模式,比如 render props 和高级组件。

函数组件

  • React 团队希望,组件不要变成复杂的容器,最好只是数据流的管道。开发者根据需要,组合管道即可。组件的最佳写法应该是函数,而不是类。
    // 函数组件的例子
    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
  • 函数组件的限制:必须是纯函数,不能包含状态,也不支持生命周期方法,无法取代类
  • React Hooks 的设计目的,就是加强版函数组件,完全不使用“类”,就可写出全功能的组件。

Hook 的含义

  • React Hooks 的意思:组件尽量写成纯函数,如果需要外部功能和副作用,就用钩子把外部代码“钩”进来。
  • 既可使用 React 官方提供的常用钩子(如 useState、useContext、useReducer、useEffect),也可以封装自己的钩子。
  • 所有的钩子都是为函数引入外部功能,所以 React 约定,钩子一律使用 use 前缀命名,便于识别。使用xxx功能,钩子就命名为 usexxx。

useState():状态钩子

  • useState() 用于为函数组件引入状态,纯函数不能有状态,所以把状态放在钩子里面。
  • useState() 这个函数接受状态的初始值,作为参数;然后返回一个数组,数组第一个成员是一个变量,指向状态的当前值。第二个成员是一个函数,用来更新状态,约定是 set 前缀加上状态的变量名。

useContext():共享状态钩子

  • useContext() 可以在组件之间共享状态

    // 第一步就是使用 React Context API,在组件外部建立一个 Context。
    const AppContext = React.createContext({});
    // 组件封装
    <AppContext.Provider value={{
      username: 'superawesome'
    }}>
      <div className="App">
        <Navbar/>
        <Messages/>
      </div>
    </AppContext.Provider>

    上面代码中,AppContext.Provider提供了一个 Context 对象,这个对象可以被子组件共享。

    // Navbar 组件
    const Navbar = () => {
      const { username } = useContext(AppContext);
      return (
        <div className="navbar">
          <p>AwesomeSite</p>
          <p>{username}</p>
        </div>
      );
    }
    // Message 组件
    const Messages = () => {
      const { username } = useContext(AppContext)
    
      return (
        <div className="messages">
          <h1>Messages</h1>
          <p>1 message for {username}</p>
          <p className="message">useContext is awesome!</p>
        </div>
      )
    }

    上面代码中,useContext()钩子函数用来引入 Context 对象,从中获取username属性。

useReducer():action 钩子

  • React 本身不提供状态管理功能,通常需要使用外部库,这方面最常用的库是 Redux。
    • Redux 的核心概念:组件发出 action 与状态管理器通信,状态管理器收到 action 以后,使用 Reducer 函数算出新的状态
    • Reducer 函数形式: (state, action) => newState
  • useReducer() 钩子用来引入 Reducer 功能。
    const [state, dispatch] = useReducer(reducer, initialState);
  • useReducer() 的基本用法:接受 Reducer 函数和状态的初始值作为参数,返回一个数组。数组的第一个成员是状态的当前值,第二个成员是发送 action 的 dispatch 函数。
    // 用于计算状态的 Reducer 函数
    const myReducer = (state, action) => {
      switch(action.type)  {
        case('countUp'):
          return  {
            ...state,
            count: state.count + 1
          }
        default:
          return  state;
      }
    }
    // 组件代码
    function App() {
      const [state, dispatch] = useReducer(myReducer, { count:   0 });
      return  (
        <div className="App">
          <button onClick={() => dispatch({ type: 'countUp' })}>
            +1
          </button>
          <p>Count: {state.count}</p>
        </div>
      );
    }
  • 由于 Hooks 可以提供共享状态和 Reducer 函数,所以它在这些方面可以取代 Redux。它目前无法取代的是:提供中间件(middleware)和时间旅行(time travel)。

useEffect():副作用钩子

  • useEffect() 用来引入具有副作用的操作,最常见的就是向服务器请求数据。以前放在 componentDidMount 里面的代码,现在可以放在 useEffect()。
    useEffect(()  =>  {
      // Async Action
    }, [dependencies])
  • useEffect() 接受两个参数,第一个参数是一个函数,异步操作的代码放在里面。第二个参数是一个数组,用于给出 Effect 的依赖项,只要这个数组发生变化,useEffect() 就会执行。(第二个参数可以省略,这时每次组件渲染时,就会执行 useEffect() )。
    const Person = ({ personId }) => {
      const [loading, setLoading] = useState(true);
      const [person, setPerson] = useState({});
    
      useEffect(() => {
        setLoading(true); 
        fetch(`https://swapi.co/api/people/${personId}/`)
          .then(response => response.json())
          .then(data => {
            setPerson(data);
            setLoading(false);
          });
      }, [personId])
    
      if (loading === true) {
        return <p>Loading ...</p>
      }
    
      return <div>
        <p>You're viewing: {person.name}</p>
        <p>Height: {person.height}</p>
        <p>Mass: {person.mass}</p>
      </div>
    }

    上面代码中,每当组件参数personId发生变化,useEffect()就会执行。组件第一次渲染时,useEffect()也会执行。

创建自己的 Hooks

  • 可以把 Hooks 代码封装成一个自定义的 Hook,便于共享。
    const usePerson = (personId) => {
      const [loading, setLoading] = useState(true);
      const [person, setPerson] = useState({});
      useEffect(() => {
        setLoading(true);
        fetch(`https://swapi.co/api/people/${personId}/`)
          .then(response => response.json())
          .then(data => {
            setPerson(data);
            setLoading(false);
          });
      }, [personId]);  
      return [loading, person];
    };

    上面代码中,usePerson()就是一个自定义的 Hook。

    const Person = ({ personId }) => {
      const [loading, person] = usePerson(personId);
    
      if (loading === true) {
        return <p>Loading ...</p>;
      }
    
      return (
        <div>
          <p>You're viewing: {person.name}</p>
          <p>Height: {person.height}</p>
          <p>Mass: {person.mass}</p>
        </div>
      );
    };

    Person 组件就改用这个新的钩子,引入封装的逻辑。

标签:const,Hooks,React,一峰,钩子,组件,return,useEffect
From: https://www.cnblogs.com/yhstsy/p/18179199

相关文章

  • TS — 在React中使用TS(基础使用)
    在React中使用TypeScript(TS)是一种很常见的做法,因为TypeScript提供了静态类型检查和其他一些有用的功能,可以帮助您更好地开发和维护React应用。1.原始组件://SimpleComponent.jsimportReactfrom'react';constSimpleComponent=({name})=>{return<div>Hel......
  • react中的state值修改了,也触发了页面的重新渲染,但是视图没有更新,可能是什么原因?
    state更新的是一个值List,但是页面渲染使用的是List中的某一项(当前选中项curItem),也定义成了state,而更新状态时,只更新了List,忽视了当前选中项curItem的状态更新,导致视图没有更新,即使组件重新渲染了,但是视图中使用的是curItem解决方案:state中不要保存当前选中项curItem,而应该保......
  • 用这个开源工具在 React 中建立一个交互式时间轴
    用这个开源工具在React中建立一个交互式时间轴作者: KarolKozer 译者: LCTT geekpi |2023-02-2409:22     Planby是一个JavaScript组件,用于帮助创建流媒体服务、音乐和体育赛事等的时间表、时间线和电子节目指南(EPG)。几年来,我在电视在线和视频点播(VOD......
  • react useEffect可以作为watch监听值变化,进行其他操作用吗
    是的,React中的useEffectHook可以被用来作为“watch”监听特定变量或状态的变化,并在这些值发生变化时执行特定的操作。这是通过在useEffect的依赖数组中列出你想要监听的值来实现的。当依赖数组中的某个值发生变化时,useEffect的回调函数会被重新执行。下面是一个简单的例子,展示......
  • mac 创建React Native项目遇到的问题
    ReactNative创建项目遇到的问题1.创建项目时提示:⠧ProcessingtemplateUsageError:Thenearestpackagedirectory(/Users/huang/Documents/develop/RN/myRn)doesn'tseemtobepartoftheprojectdeclaredin/Users/huang.-If/Users/huangisn'tintendedtobe......
  • [Unit testing - React] Use the waitForElementToBeRemoved Async Util to Await Unt
    Sometimes,youmightneedtowaitforanelementtodisappearfromyourUIbeforeproceedingwithyourtestsetupormakingyourassertion.Inthislesson,wewilllearnaboutawrapperaroundthewaitForthatallowsyoutowaituntilanelementisremove......
  • [Unit Testing - React] Use the Testing Playground to Help Decide Which Query to
    Queryingisdifficult!Evenifwefollowtheguidingprinciplesandalwaysstartfromthequeriesaccessibletoeveryone,weareboundtogetstucksometimes.Tohelpusout,theTestingPlaygroundwascreated.Inthislesson,wearegoingtoseehowtou......
  • 界面控件DevExtreme v23.1、v23.2盘点 - 增强的TypeScript(Angular、React、Vue)
    DevExtreme拥有高性能的HTML5/JavaScript小部件集合,使您可以利用现代Web开发堆栈(包括React,Angular,ASP.NETCore,jQuery,Knockout等)构建交互式的Web应用程序。从Angular和Reac,到ASP.NETCore或Vue,DevExtreme包含全面的高性能和响应式UI小部件集合,可在传统Web和下一代移动应用程序中......
  • react中事件冒泡导致弹窗关不掉
    代码如下<Modalactions={[{text:'Cancel',variant:'secondary',onClick:()=>setDeleteAutomatedReportModalVisible(false),},/>点击Cancel按钮,弹窗应该关闭才对,......
  • React入门
    React极简入门:从JavaScript到React-知乎(zhihu.com) HTML<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>Mytestpage</title></head><body><h1>这是标题一</h1>......