6、react-useReducer初体验、useReducer和useContext结合使用

  1. 初次体验
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>
		</>
	)

}
  1. useReduceruseContext结合使用
  • 主页面组件
import React from 'react'
import { Color } from './color'
import { Content } from './content'
const Demo = () => {
    return (
        <Color>
            <Content></Content>
        </Color>
    )
}
export default Demo
  • Color 组件
import React, { createContext, useReducer } from 'react'
const ColorContext = createContext(null) //提供全局ColorContext

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
}
  • Content组件
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>
        </>
    )
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值