React Hook使用

Hook是React 16.8 的新增特性。

  • 在hook出现之前,使用react有一些痛点,简单整理如下几点: 由于业务变动,函数组件必须不得不改为类组件 组件逻辑复杂时难以开发和维护
    一个逻辑难以跨组件使
  • 目的:加强函数组件,完全不使用"类",就能写出一个全功能的组件。

使用限制:
1、只能在函数最外层调用 Hook。不要在循环、条件判断或者子函数中调用。
2、只能在 React 的函数组件中调用
Hook。不要在其他 JavaScript 函数中调用。(还有一个地方可以调用 Hook —— 就是自定义的 Hook 中。)

https://uploader.shimo.im/f/ctx6NdJyEfxDX2Ip.png

import React, { PureComponent, useState } from 'react';export default class Counter extends PureComponent {render () {const count = 1;return (<h1>{count}碗大碗宽面</h1>);}
}
import React from 'react';export default function Counter() {const count = 1;return (<h1>{count}碗大碗宽面</h1>);
}

这种写法有重大限制,必须是纯函数,不能包含状态,也不支持生命周期方法,因此无法取代类

Hook
useState
useEffect
useCallback
useContext
useReducer
useMemo
useRef
useImperativeHandle
useLayoutEffect
useDebugValue

ueState

1、返回一对值(当前值和一个让你更新它的函数)
2、通过在函数组件里来调用它给组件添加一些内部state,react会在重新渲染时保留这个state

类组件

import React, { PureComponent, useState } from 'react';
import { Button } from 'antd-mobile';export default class Counter extends PureComponent {constructor(props) {super(props);this.state = { count: 1 };}render () {const { count } = this.state;return (<div><h1>{count}碗大碗宽面</h1><Button onClick={() => this.setState({ count: count + 1 })}>加一碗</Button></div>);}
}

函数组件

import React, { useState } from 'react';
import { Button } from 'antd-mobile';export default function Counter() {const [count, setCount] = useState(1);return (<div><h1>{count}碗大碗宽面</h1><Button onClick={() => setCount(count + 1)}>加一碗</Button></div>);
}

状态:既放在state中的变量,比如上面例子中的count
更改状态的函数:类似class组件中的this.setState,上面例子的setCount,通过setCount(count+1)重新赋值更改状态
初始状态:在初始化hook的时候通过useState(1)赋值,其中1就是初始状态

useEffect

class组件

import React from 'react';
import { Button, Toast } from 'antd-mobile';export default class Counter extends React.Component {constructor(props) {super(props);this.state = {count: 1,big: true,type: '宽面'};}componentDidMount() {if (this.state.type !== '宽面') {Toast.info('今天只能吃宽面');}}componentDidUpdate() {if (this.state.type !== '宽面') {Toast.info('今天只能吃宽面');}}render() {const { count, big, type } = this.state;const size = big ? '大' : '小';return (<div><div>{count}{size(big)}{type}</div><Button onClick={() => this.setState({ count: count + 1 })} style={{ 'height': '40px' }}>加一碗</Button><Button onClick={() => this.setState({ big: !big })} style={{ 'height': '40px' }}>{size}</Button><Button onClick={() => this.setState({ type: '细面' })} style={{ 'height': '40px' }}>不想吃宽面</Button></div>);}
}

使用useEffect

import React, { useEffect, useState } from 'react';
import { Button, Toast } from 'antd-mobile';export default function Counter() {const [count, setCount] = useState(1);const [big, setSize] = useState(true);const [type, setType] = useState('宽面');const size = big ? '大' : '小';useEffect(() => {if (type !== '宽面') {Toast.info('今天只能吃宽面');}});return (<div><div>老板,来{count}{size(big)}{type}</div><Button onClick={() => setCount(count + 1)}>加一碗</Button><Button onClick={() => setSize(!big)}>{size}</Button><Button onClick={() => setType('细面')}>不想吃宽面</Button></div>);
}

useEffect参数

1、如果什么都不传,会在每次渲染后都执行,也就是说在第一次渲染之后和每次更新之后都会执行。
2、如果传一个空数组,那么就只会运行一次effect,并且effect内部的 props 和 state 会一直拥有其初始值。
3、如果传的是一个包含属性值的数组,那么只有当数组里的值发生变化的时候才会触发useEffect回调。

// 相当于 componentDidMount 和 componentDidUpdate
useEffect(() => {console.log(`You clicked ${count} times`);
});// 由于第二个参数传的是空数组,所以这里相当于componentDidMount
useEffect(() => {...// 相当于componentWillUnmountreturn () => {};
}, []);// 相当于 componentDidMount 和 componentDidUpdate
useEffect(() => {console.log(`You clicked ${count} times`);
}, [count]);

对比于以前react class的写法,可以把useEffect看做
componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。

自定义Hook

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

参考资料

React Hooks 入门教程
http://www.ruanyifeng.com/blog/2019/09/react-hooks.html
react 16.7 hook概述
https://www.jianshu.com/p/e61faf452565
hook详解
https://blog.csdn.net/tonydz0523/article/details/106479182
React Hooks 拓展钩子和自定义Hook的使用
https://www.jianshu.com/p/0510d6f83dce
理解React Hooks
https://www.jianshu.com/p/d6244228a427


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部