• 使用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;
  • 相关阅读:
    ARM启动流程
    ARM机器码分析
    Ubuntu 14.04 dnw配置
    UNIX环境下的消息队列
    UNIX环境下的共享内存
    iptables详解
    iptables 相关名词的解释说明
    sphinx的安装配置和中文分词包coreseek
    linux防火墙iptables封IP,拒绝指定IP和网段的办法
    linux下注销其它用户或者tty的命令
  • 原文地址:https://www.cnblogs.com/-roc/p/15137508.html
Copyright © 2020-2023  润新知