useReducer
总的来说useReducer是useState的复杂版和redux差不多
import React, { useState, useReducer, createContext, useContext, useEffect, useMemo, useRef } from 'react';
const initial = {
n: 0
};
//创建初始值
const reducer = (state: any, action: any) => {
//创建所有操作reducer(state,action)
if (action.type === "add") {
return { n: state.n + action.number };
} else if (action.type === "multi") {
return { n: state.n - action.number };
} else {
throw new Error("unknown type");
}
};
function App() {
const [state, dispatch] = useReducer(reducer, initial);
const { n } = state;
const onClick = () => {
dispatch({ type: "add", number: 1 });
// 传给reducer()进行操作修改值
};
const onClick2 = () => {
dispatch({ type: "multi", number: 2 });
};
return (
<div className="App">
<h1>n: {n}</h1>
<button onClick={onClick}>+1</button>
<button onClick={onClick2}>+2</button>
</div>
);
}
export default App;
除了没有使用到高阶组件外都是差不多的,后面会说到如何用useReducer + Context替代Redux
useRef
如果你需要一个值在组件不断render时 保持不变 ,那么你就会用到 useRef()
因为useRef()创建了一个普通的JavaScript对象。useRef()与{current: …}自己创建对象之间的唯一区别是,useRef它将在每个渲染器上为您提供相同的ref对象。
请记住,内容更改时useRef 不会通知您。对该.current属性进行突变不会导致重新渲染
import React, { useState, useReducer, createContext, useContext, useEffect, useMemo, useRef } from 'react';
import { render } from '@testing-library/react';
function App() {
console.log("app执行了")
const count = useRef(0)//在没一次渲染的时候都不会重新 变化 都是同一个
const [n, setN] = useState(0)
const onclick = () => {
setN(n + 9)
}
useEffect(() => {
count.current += 1
console.log(count.current)
})
return (
<div className="sss">
<button onClick={onclick}>我是N吧</button>
</div>
);
}
export default App;
/**
*
* 如果你需要一个值在组件不断render时 保持不变 useRef(0)
* 初始化 const count =useRef(0)
* 读取:count.current
*
* 为什么需要current?
* 为了保证两次useRef 是同一个值
* 他不会刷新UI
*
*/
详细请参见 官网介绍