1.useState
用于声明一个state变量,例子如下
点击查看代码
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>
);
}
2.useEffect
有类似于类组件中的生命周期之类函数的作用,用于处理组件中的副作用操作,比如数据获取、DOM操作等。不传参数时所有的更新都会触发,传递空数据为参数时仅在挂载和卸载的时候执行,传递一个值时仅在这个值更新时执行
点击查看代码
//1.不传值时
useEffect(()=>{
console.log(props.number)
setNumber(props.number)
}) //所有更新都执行
//2.传递空数组
useEffect(()=>{
console.log(props)
},[]) //仅在挂载和卸载的时候执行
//3.传递一个值
useEffect(()=>{
console.log(count)
},[count]) //count更新时执行
3.useContext
没有hooks之前,类组件通过props进行父子组件之间的数据传输,有了hooks之后函数组件通过useContext进行父子组件之间的数据传输
点击查看代码
import React, { useState, createContext, useContext } from "react";
const CountContext = createContext(0);
const Example = () => {
const [count, setCount] = useState<number>(0);
return (
<div>
<p>父组件点击数量:{count}</p>
<button onClick={() => setCount(count + 1)}>{"点击+1"}</button>
<CountContext.Provider value={count}>
<Counter />
</CountContext.Provider>
</div>
);
};
const Counter = () => {
const count = useContext(CountContext);
return <p>子组件获得的点击数量:{count}</p>;
};
export default Example;
4.useReducer
useReducer 是 useState 的升级版本,用来践行 Flux/Redux 的思想,可以使用useReducer来代替Redux
点击查看代码
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</>
);
}