react-hook

react16.8新增特性,它可以让你在不编写class的情况下使用state及其它react特性

hook可取代class的使用

hook产生的原因:
1.解决组件间复用状态逻辑难的问题

2.复杂组件变得难以理解

hook使用规则:

1.只能在函数最外层调用hook,不要在循环、条件判断或子函数中调用

2.只能在react得函数组件中调用hook。不要在其它JavaScript函数中调用。

3.自定义hook中也可以调用hook

规范hook使用规则的插件:

eslint-plugin-react-hooks

"react-hooks/rules-of-hooks": "error", // 检查 Hook 的规则

"react-hooks/exhaustive-deps": "warn" // 检查 effect 的依赖

useState用法:

声明变量:

const [age,setAge]=useState(42)

const [fruit,setFruit]=useState('banana')

const [todos,setTodos] = useState([{text:'学习hook'}])

单独更新值:

setFruit('orange')

hook与class的对于写法:

//HOOK写法

import React, { useState } from 'react';

function Example() {
  // 声明一个叫 "count" 的 state 变量
  const [count, setCount] = useState(0);

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

//Class写法
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

useEffect Hook用法:

useEffect hook可以看作componentDidMount、componentDidUpdate和componentWillUnmount这三个函数的组合。在第一次渲染之后和每次更新之后都会执行

import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    // Specify how to clean up after this effect:
    return function cleanup() {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  });

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

自定义hook:

1.必须以use开头

 
 
posted @ 2020-12-07 17:54  吃草的虾米  阅读(110)  评论(0编辑  收藏  举报