首页 > 其他 > 详细

使用useReducer 实现 todoList

时间:2021-08-13 17:30:50      阅读:28      评论:0      收藏:0      [点我收藏+]
// 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;

 

使用useReducer 实现 todoList

原文:https://www.cnblogs.com/-roc/p/15137508.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!