React Hook 的使用

305 阅读2分钟
Hooks是React v16.7.0-alpha中加入的新特性。它可以让你在class以外使用state和其他React特性


1.state hook的使用

useState是一个Hook,它允许您将React状态添加到功能组件(常说的无状态组件)

使用场景:如果你编写一个函数组件并意识到你需要为它添加一些状态,那么之前你必须将它转换为一个类。现在,您可以在现有功能组件中使用useState

例如:

 //我们useState从React 导入Hook。它允许我们将本地状态保存在功能组件中
import { useState } from 'react';

function Example() {
  //count 相当于this.state.count  useState(0)相当于this.setState({conut:0}) 
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

等效于

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>
    );
  }
}

使用state的属性

<p>这是之前的state使用方式 {this.state.count}</p>
<p>在React v16.7.0-alpha可以这么用 {count} </p>

修改state的值

<button onClick={() => this.setState({ count: this.state.count + 1 })}>
    这是之前的修改方式
  </button>
<button onClick={() => setCount(count + 1)}>
   React v16.7.0-alpha可以这么用
  </button>

2.Effect Hook的使用

你可以把 useEffect Hooks 视作 componentDidMountcomponentDidUpdatecomponentWillUnmount 的结合

我们在 React 更新 DOM 之后立刻更新 document title

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

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }

  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

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

等效于

import { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);
  //默认情况下 它会在第一次 render 和之后的每次 update 后运行
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

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