- 初次体验
import React, { useState, useEffect, useReducer } from 'react';
export const Demo = () => {
const [conut, setCount] = useReducer((state, action) => {
switch (action) {
case 'increment':
return state + 1
case 'decrement':
return state - 1
default:
return state
}
}, 0)
return (
<>
<span>{conut}</span>
<Button onClick={() => { setCount('increment') }}>+</Button>
<Button onClick={() => { setCount('decrement') }}>-</Button>
</>
)
}
- useReducer和useContext结合使用
import React from 'react'
import { Color } from './color'
import { Content } from './content'
const Demo = () => {
return (
<Color>
<Content></Content>
</Color>
)
}
export default Demo
import React, { createContext, useReducer } from 'react'
const ColorContext = createContext(null)
const reducer = (state, action) => {
if (action?.type == 'UPDATE_COLOR') return action.color
return state
}
const Color = props => {
const [color, dispatch] = useReducer(reducer, 'red')
return (
<ColorContext.Provider value={{ color, dispatch }}>
{props.children}
</ColorContext.Provider>
)
}
export {
ColorContext,
Color
}
import React, { useContext } from 'react'
import { Button } from 'antd'
import { ColorContext } from './color'
export const Content = () => {
const { color, dispatch } = useContext(ColorContext)
return (
<>
<p style={{ color }}>你看我是什么颜色</p>
<Button onClick={() => { dispatch({ type: 'UPDATE_COLOR', color: 'green' }) }}>变绿</Button>
<Button onClick={() => { dispatch({ type: 'UPDATE_COLOR', color: 'yellow' }) }}>变黄</Button>
</>
)
}