ctrlcv-dev.comgithub

React Hookscheatsheet

贡献者:BAI

React Hooks

Hook 是 React 16.8 的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性。

JSX
import React, { useState } from "react";
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}

详见: Hooks at a Glance

Effect hook

JSX
import React, { useState, useEffect } from "react";
function Example() {
const [count, setCount] = useState(0);
// 与 componentDidMount 和 componentDidUpdate 作用相似
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}

如果您熟悉 React 类的生命周期方法,则可以将useEffect Hook 视为 componentDidMountcomponentDidUpdatecomponentWillUnmount 的组合。 默认情况下,React 在每个渲染后(包括第一个渲染)运行 effects。

构建自己的 hooks

定义 FriendStatus

JSX
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);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
}, [props.friend.id]);
if (isOnline === null) {
return "Loading...";
}
return isOnline ? "Online" : "Offline";
}

Effects 也可以有选择地指定如何通过返回函数来进行“清理”。

使用 FriendStatus

JSX
function FriendStatus(props) {
const isOnline = useFriendStatus(props.friend.id);
if (isOnline === null) {
return "Loading...";
}
return isOnline ? "Online" : "Offline";
}

详见: Building Your Own Hooks

Hooks API 参照

也可以查看: Hooks FAQ

Basic Hooks

HookDescription
useState(initialState)
useEffect(() => { ... })
useContext(MyContext)value returned from React.createContext

查看更多: Basic Hooks

额外的 Hooks

HookDescription
useReducer(reducer, initialArg, init)
useCallback(() => { ... })
useMemo(() => { ... })
useRef(initialValue)
useImperativeHandle(ref, () => { ... })
useLayoutEffectidentical to useEffect, but it fires synchronously after all DOM mutations
useDebugValue(value)display a label for custom hooks in React DevTools

查看更多: Additional Hooks

声明多 state 变量

JSX
function ExampleWithManyStates() {
// Declare multiple state variables!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState("banana");
const [todos, setTodos] = useState([{ text: "Learn Hooks" }]);
// ...
}