react hooks是什么?


本文摘自PHP中文网,作者青灯夜游,侵删。

React hooks是React16.8的新特性,可以让React函数组件具有状态,并提供类似componentDidMount和componentDidUpdate等生命周期方法。

我们大部分 React 类组件可以保存状态,而函数组件不能? 并且类组件具有生命周期,而函数组件却不能?

React 早期版本,类组件可以通过继承PureComponent来优化一些不必要的渲染,相对于函数组件,React 官网没有提供对应的方法来缓存函数组件以减少一些不必要的渲染,直接 16.6 出来的 React.memo函数。

React 16.8 新出来的Hooks可以让React 函数组件具有状态,并提供类似 componentDidMount和componentDidUpdate等生命周期方法。

Hook 这个单词的意思是"钩子"。

React Hooks 的意思是,组件尽量写成纯函数,如果需要外部功能和副作用,就用钩子把外部代码"钩"进来。 React Hooks 就是那些钩子。

你需要什么功能,就使用什么钩子。React 默认提供了一些常用钩子,你也可以封装自己的钩子。

所有的钩子都是为函数引入外部功能,所以 React 约定,钩子一律使用use前缀命名,便于识别。你要使用 xxx 功能,钩子就命名为 usexxx。

下面介绍 React 默认提供的四个最常用的钩子。

  • useState()

  • useContext()

  • useReducer()

  • useEffect()

useState():状态钩子

useState()用于为函数组件引入状态(state)。纯函数不能有状态,所以把状态放在钩子里面。

本文前面那个组件类,用户点击按钮,会导致按钮的文字改变,文字取决于用户是否点击,这就是状态。使用useState()重写如下。

1

2

3

4

5

6

7

8

import React, { useState } from "react";

export default function  Button()  {

  const  [buttonText, setButtonText] =  useState("Click me,   please");

  function handleClick()  {

    return setButtonText("Thanks, been clicked!");

  }

  return  <button  onClick={handleClick}>{buttonText}</button>;

}

demo地址:https://codesandbox.io/s/nifty-waterfall-4i2dq

上面代码中,Button 组件是一个函数,内部使用useState()钩子引入状态。

useState()这个函数接受状态的初始值,作为参数,上例的初始值为按钮的文字。该函数返回一个数组,数组的第一个成员是一个变量(上例是buttonText),指向状态的当前值。第二个成员是一个函数,用来更新状态,约定是set前缀加上状态的变量名(上例是setButtonText)。

useContext():共享状态钩子

如果需要在组件之间共享状态,可以使用useContext()。

现在有两个组件 Navbar 和 Messages,我们希望它们之间共享状态。

1

2

3

4

<div className="App">

  <Navbar/>

  <Messages/>

</div>

第一步就是使用 React Context API,在组件外部建立一个 Context。

1

const AppContext = React.createContext({});

组件封装代码如下。

1

2

3

4

5

6

7

8

<AppContext.Provider value={{

  username: 'superawesome'

}}>

  <div className="App">

    <Navbar/>

    <Messages/>

  </div>

</AppContext.Provider>

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

Navbar 组件的代码如下。

1

2

3

4

5

6

7

8

9

const Navbar = () => {

  const { username } = useContext(AppContext);

  return (

    <div className="navbar">

      <p>AwesomeSite</p>

      <p>{username}</p>

    </div>

  );

}

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

Message 组件的代码也类似。

1

2

3

4

5

6

7

8

9

10

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>

  )

}

demo:https://codesandbox.io/s/react-usecontext-redux-0bj1v

useReducer():action 钩子

React 本身不提供状态管理功能,通常需要使用外部库。这方面最常用的库是 Redux。

Redux 的核心概念是,组件发出 action 与状态管理器通信。状态管理器收到 action 以后,使用 Reducer 函数算出新的状态,Reducer 函数的形式是(state, action) => newState。

useReducers()钩子用来引入 Reducer 功能。

1

const [state, dispatch] = useReducer(reducer, initialState);

上面是useReducer()的基本用法,它接受 Reducer 函数和状态的初始值作为参数,返回一个数组。数组的第一个成员是状态的当前值,第二个成员是发送 action 的dispatch函数。

下面是一个计数器的例子。用于计算状态的 Reducer 函数如下。

1

2

3

4

5

6

7

8

9

10

11

const myReducer = (state, action) => {

  switch(action.type)  {

    case('countUp'):

      return  {

        ...state,

        count: state.count + 1

      }

    default:

      return  state;

  }

}

组件代码如下。

1

2

3

4

5

6

7

8

9

10

11

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>

  );

}

demo:https://codesandbox.io/s/react-usereducer-redux-xqlet

由于 Hooks 可以提供共享状态和 Reducer 函数,所以它在这些方面可以取代 Redux。但是,它没法提供中间件(middleware)和时间旅行(time travel),如果你需要这两个功能,还是要用 Redux。

useEffect():副作用钩子

useEffect()用来引入具有副作用的操作,最常见的就是向服务器请求数据。以前,放在componentDidMount里面的代码,现在可以放在useEffect()。

useEffect()的用法如下。

1

2

3

useEffect(()  =>  {

  // Async Action

}, [dependencies])

上面用法中,useEffect()接受两个参数。第一个参数是一个函数,异步操作的代码放在里面。第二个参数是一个数组,用于给出 Effect 的依赖项,只要这个数组发生变化,useEffect()就会执行。第二个参数可以省略,这时每次组件渲染时,就会执行useEffect()。

下面看一个例子。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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()也会执行。

demo:https://codesandbox.io/s/react-useeffect-redux-9t3bg

创建自己的 Hooks

上例的 Hooks 代码还可以封装起来,变成一个自定义的 Hook,便于共享。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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。

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

1

2

3

4

5

6

7

8

9

10

11

12

13

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>

  );

};

demo:https://codesandbox.io/s/react-useeffect-redux-ghl7c

更多编程相关知识,请访问:编程学习网站!!

以上就是react hooks是什么?的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

React中怎么改变state的值

React如何阻止冒泡失败

redux如何关联React

tomcat如何部署React项目

React怎么循环map

混合开发可以用React

有哪些React多端统一框架?

React中的portal是做什么的

vue和React属于js库吗

angular与angularjs、React和vue的简单对比

更多相关阅读请进入《React》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...