使用useReducer 实现 todoList

// useReducer 实现 todoList
import React,{ useReducer,useRef } from 'react'
import './index.less'

function todoList() {
  const inputRef = useRef();

  /*
    https://react.docschina.org/docs/hooks-reference.html?#usereducer
    useState 的替代方案。
    它接收一个形如 (state, action) => newState 的 reducer,并返回当前的 state 以及与其配套的 dispatch 方法。
    (如果你熟悉 Redux 的话,就已经知道它如何工作了。)
  */

  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(){
    dispatch({
      type:'add',
      name:inputRef.current.value
    });
    inputRef.current.value = '';
  }

  return (
    <>
      <div>
        <input ref={inputRef}/>
        <button onClick={() => handleSubmit()}>添加</button>
        <button className="is-danger" onClick={() => dispatch({type:'clear'})}>清空</button>
      </div>
      <ul>
        {items.map((item,index) => (
          <li key={item.id}>
            {item.name}
            <button onClick={() => dispatch({type:'remove',index})}>删除</button>
          </li>
        ))}
      </ul>
    </>
  )
}
export default todoList;
原文地址:https://www.cnblogs.com/-roc/p/15137508.html