首先明確一點,Redux 是一個有用的架構,但不是非用不可。事實上,大多數情況,你可以不用它,只用 React 就夠了。
曾經有人說過這樣一句話。
"如果你不知道是否需要 Redux,那就是不需要它。"
Redux 的創造者 Dan Abramov 又補充了一句。
"只有遇到 React 實在解決不了的問題,你才需要 Redux 。"
redux使用教程
回歸正題
如何使用context+useReducer來做類似於Vuex一樣的全局狀態管理.
- 首先使用create-react-app創建項目
npx create-react-app my-app cd my-app npm start
2. 在src目錄下創建state文件夾,里面只有一個index.js文件
src
| ---- state
| ------index.js
...
3. state>index.js代碼如下
import React, { useReducer } from "react" //導入react,
const State = React.createContext() //創建Context對象,來向組件樹傳遞數據
//定義reducer的改變規則
const ADD = "ADD"
const DECREASE = "DECREASE"
function reducer(state, action) {
switch (action) {
case ADD:
return state + 1
case DECREASE:
return state - 1
default:
return state
}
}
//定義一個組件來包裹需要獲取到共享數據的組件
const StateProvider = props => {
//獲取值和設置值的方法,0是默認值
const [state, dispatch] = useReducer(reducer, 0)
/* value 就是組件樹能夠拿到的數據,傳了一個state值,和一個dispatch方法
dispatch就是為了改變state用的 */
return <State.Provider value={{ state, dispatch }}>
{props.children}
</State.Provider>
}
export {
State, StateProvider, ADD, DECREASE
}
4. src目錄下只留下state文件夾,index.js文件,App.js文件,新建components文件夾
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { StateProvider } from "./state"
ReactDOM.render(
<StateProvider>
<App />
</StateProvider>,
document.getElementById('root')
);
src/App.js
import React, { useContext } from "react"
import MyComponents01 from "./components/MyComponents01"
import { State, ADD, DECREASE } from "./state" //取出context對象
export default function App() {
const { dispatch }=useContext(State) //獲取到dispatch
return <>
<h1>計數器:</h1>
<div>
<button onClick={()=> dispatch(ADD)}>+1</button>
<button onClick={()=> dispatch(DECREASE)}>-1</button>
</div>
<MyComponents01 />
</>
}
src/components/MyComponents01.js
import React, { useContext } from "react"
import { State } from "../state" //取出context對象
export default function MyComponents01(){
//取出共享的數據state
const { state }=useContext(State)
return <div>
共享數據:{state}
</div>
}
最終效果
tips
只要在Provide組件下, 所有的組件都可以獲取到共享數據,
獲取共享數據也很簡單.引入Context對象
在組件內部使用const { ... } =useContext(創建的Context對象)即可
