1, 函数化组件HOOK
- Hook 是一个特殊的函数,它可以让你“钩入” React 的特性。例如,useState 是允许你在 React 函数组件中添加 state 的 Hook, 之前的可以叫无状态组件
- Hook 在 class 内部是不起作用的。但你可以使用它们来取代 class 。
- 在 class 中,我们通过在构造函数中设置 this.state 为 { count: 0 } 来初始化 count state 为 0:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
在函数组件中,我们没有 this,所以我们不能分配或读取 this.state。我们直接在组件中调用 useState Hook:
import React, { useState } from 'react';
function Example() {
// 声明一个叫 “count” 的 state 变量
const [count, setCount] = useState(0);
- Effect Hook 副作用钩子,可以把 useEffect Hook 看做 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
如果想执行一次, 例如API的调用, 可以在第二个参数设置为空数组, 类似于componentDidMount的作用
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
// API 调用
document.title = `You clicked ${count} times`;
}, []);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
2, 组件跨层级通信 - context 解决组件隔代传参问题
- Context 提供了一个无需为每层组件手动添加 props,就能在组件树间进行数据传递的方法。
- 在一个典型的 React 应用中,数据是通过 props 属性自上而下(由父及子)进行传递的,但这种做法对于某些类型的属性而言是极其繁琐的(例如:地区偏好,UI 主题),这些属性是应用程序中许多组件都需要的。Context 提供了一种在组件之间共享此类值的方式,而不必显式地通过组件树的逐层传递 props。
- Context 设计目的是为了共享那些对于一个组件树而言是“全局”的数据,例如当前认证的用户、主题或首选语言。
// 隔代传惨
import React, {useContext} from 'react'
// 1,使用上下文
const MyContext = React.createContext()
const {Provider, Consumer} = MyContext
function Child(prop) {
return <div>Child: {prop.foo}</div>
}
// 2,使用Hook消费
function Child2() {
const ctx = useContext(MyContext)
console.log(ctx)
return <div>Child2: {ctx.foo}</div>
}
// 3,使用class指定静态contextType
class Child3 extends React.Component {
static contextType = MyContext
render() {
return <div>Child3: {this.context.foo}</div>
}
}
export default function ContextText() {
return (
<div>
<Provider value={{foo: "bar"}}>
{/*1,Consumer*/}
<Consumer>
{value => <Child {...value} />}
</Consumer>
{/*2,HOOK*/}
<Child2></Child2>
{/*3,class*/}
<Child3></Child3>
</Provider>
</div>
)
}
渲染结果