usereducer和usecontext實(shí)現(xiàn)redux視頻地址
文章地址
React Hook 中 createContext & useContext 這篇文章講的很不錯
從技術(shù)胖那看了視頻小案例分為四個組件
通過useReducer和useContext實(shí)現(xiàn) 在不同組件點(diǎn)擊按鈕字體變色

image.png
思路:
先把所有代碼貼上
Text.js
import React, { useContext } from 'react';
import { ColorContext } from './Color'
export default function Text() {
const { color,dispatch } = useContext(ColorContext)
console.log(color);
console.log(dispatch);
return (<div style={{ color: color }}>字體顏色為{color}</div>)
}
Color.js
import React, { createContext, useReducer } from 'react';
const ColorContext = React.createContext({})
const reducer = (state, action) => {
switch (action.type) {
case UPDATE_COLOR:
return action.color
default:
return state
}
}
const UPDATE_COLOR = 'UPDATE_COLOR'
export default function Color(props) {
const [color, dispatch] = useReducer(reducer, 'blue')
return <ColorContext.Provider value={{color, dispatch}}>
{props.children}
</ColorContext.Provider>
}
export {
ColorContext,
reducer,
UPDATE_COLOR
}
Button.js
import React, { createContext, useReducer } from 'react';
const ColorContext = React.createContext({})
const reducer = (state, action) => {
switch (action.type) {
case UPDATE_COLOR:
return action.color
default:
return state
}
}
const UPDATE_COLOR = 'UPDATE_COLOR'
export default function Color(props) {
const [color, dispatch] = useReducer(reducer, 'blue')
return <ColorContext.Provider value={{color, dispatch}}>
{props.children}
</ColorContext.Provider>
}
export {
ColorContext,
reducer,
UPDATE_COLOR
}
App.js
import React, { createContext, useReducer } from 'react';
const ColorContext = React.createContext({})
const reducer = (state, action) => {
switch (action.type) {
case UPDATE_COLOR:
return action.color
default:
return state
}
}
const UPDATE_COLOR = 'UPDATE_COLOR'
export default function Color(props) {
const [color, dispatch] = useReducer(reducer, 'blue')
return <ColorContext.Provider value={{color, dispatch}}>
{props.children}
</ColorContext.Provider>
}
export {
ColorContext,
reducer,
UPDATE_COLOR
}