V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Allianzcortex
V2EX  ›  React

把 React 的 todoMVC 用 Hooks 重新改写了一遍

  •  
  •   Allianzcortex · 2020-02-02 11:36:49 +08:00 · 1361 次点击
    这是一个创建于 1545 天前的主题,其中的信息可能已经有所发展或是发生改变。

    是很久以前写的一个东西了,当时在学 Hooks 的时候想要找一个实现 todomvc 的例子来作为 demo 学习,网上找到的一个例子是: https://github.com/sokra/todo-mvc-react-hooks-experiments, 但它只用了 useState 而没有用 redux,于是就把 react 最经典的一个 todomvc 用 useState/useSelector/useDispatch 和纯 function class 改写了一遍。顺便除去了所有的 container component 让逻辑更集中一些。

    const Link = ({ filter,children }) =>{
    
      const active = useSelector(state=>state.visibilityFilter===filter)
      const dispatch=useDispatch();
      
      return (
        // eslint-disable-next-line jsx-a11y/anchor-is-valid
        <a
          className={classnames({ selected: active })}
          style={{ cursor: 'pointer' }}
          onClick={() =>{dispatch(setVisibilityFilter(filter))}}
        >
          {children}
        </a>
      )}
    
    
      }
      
    

    因为没有与网络的交互就暂时没有用 useEffect 去实现各种生命周期函数。整个没什么太大难度吧,如果以后有同学想看 redux hooks 的例子可以做个参考。

    repo : https://github.com/Allianzcortex/code_collection/tree/dev/react-todomvc-only-hooks-without-mapstate

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2211 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 00:32 · PVG 08:32 · LAX 17:32 · JFK 20:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.