全面掌握 React — useReducer


在 hooks 中提供了的 useReducer 功能,可以增强 ReducerDemo 函数提供类似 Redux 的功能,引入 useReducer 后,useReducer 接受一个 reducer 函数作为参数,reducer 接受两个参数一个是 state 另一个是 action 。然后返回一个状态 count 和 dispath,count 是返回状态中的值,而 dispatch 是一个可以发布事件来更新 state 的。

export default function ReducerDemo() {
    const [count, dispath] = useReducer((state,action)=> {
        if(action === 'add'){
            return state + 1;
        }
        return state;
    }, 0);
    return (
        >
            

className="title">{count}>

下面的代码并不没有什么特别,只是在上面代码基础进行巩固,大家可以自己阅读一下。

import React,{ useReducer,useRef } from 'react'

export default function ShoppingList() {
    const inputRef = useRef();
    const [items, dispatch] = useReducer((state,action)=> {
        switch(action.type){
            case 'add':
                return [...state,
                    {
                        id:state.length,
                        name:action.name
                    }]
                }
    },[])
    
    function handleSubmit(event){
        event.preventDefault();
        dispatch({
            type:'add',
            name:inputRef.current.value
        });
        inputRef.current.value = '';
    }
    
    return (
        <>
            
onSubmit={handleSubmit}> ref={inputRef}/> > > {items.map(item => (
  • key={item.id}>{item.name}> ))} > > ) }
  • 这里值得说一下就是 ...state 这是每一次我们需要 copy 一个 state 然后修改 state 而不是在 state 原有对象进行修改。这就是 immutable 数据吧。

    import React,{ useReducer,useRef } from 'react'
    
    export default function ShoppingList() {
        const inputRef = useRef();
        const [items, dispatch] = useReducer((state,action)=> {
            switch(action.type){
                case 'add':
                    return [...state,
                        {
                            id:state.length,
                            name:action.name
                        }]
    
                case 'remove':
                    return state.filter((_,index) => index != action.index)
    
                case 'clear':
                    return [];
                default:
                    return state;
                }
        },[])
        
        function handleSubmit(event){
            event.preventDefault();
            dispatch({
                type:'add',
                name:inputRef.current.value
            });
            inputRef.current.value = '';
        }
        
        return (
            <>
                ={handleSubmit}>
    
                    ={inputRef}/>
                </form>
                


    作者:zidea
    链接:https://www.jianshu.com/p/14e429e29798
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。