usereducer和usecontext实现redux视频地址
文章地址
React Hook 中 createContext & useContext 这篇文章讲的很不错
从技术胖那看了视频小案例分为四个组件
通过useReducer和useContext实现 在不同组件点击按钮字体变色
思路:
先把所有代码贴上
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
}