关注分离,合理复用

  • 展示组件(Presentational components): components that just render HTML and are primarily concerned with how things look.
  • 业务逻辑(Business logic): logic defined by the business/client (like manipulating data: sorting, calculations etc)
  • 执行逻辑(Implementation logic): intermediate logic that makes your app work, connects business logic to your presentational components (manipulating the DOM, state changes, network requests etc). This is usually done using frameworks. ```typescript // Presentational component const QuantitySelector = () => { const { onClickPlus, onClickMinus, state } = useQuantitySelector(); const { message, value } = state; return (
    1. <button onClick={onClickMinus} className="button">
    2. -
    3. </button>
    4. <div className="number">{value}</div>
    5. <button onClick={onClickPlus} className="button">
    6. +
    7. </button>
    8. <div className="message">{message}</div>
    ); };

// Business logic. Pure, testable, atomic functions const increase = (prevValue, max) => { return { value: prevValue < max ? prevValue + 1 : prevValue, message: prevValue < max ? “” : “Max!” }; };

const decrease = (prevValue, min) => { return { value: prevValue > min ? prevValue - 1 : prevValue, message: prevValue > min ? “” : “Min!” }; };

// Implementation/framework logic. Encapsulating state and effects here const useQuantitySelector = () => { const [state, setState] = useState({ value: 0, message: “” }); const onClickPlus = () => { setState(increase(state.value, 10)); }; const onClickMinus = () => { setState(decrease(state.value, 0)); }; return { onClickPlus, onClickMinus, state }; }; ```

参考资料

  1. 代码简洁之道:编写干净的 React Components & JSX
  2. React Hooks 实践指南 #13
  3. 业务中的组件化体系
  4. Separating responsibilities in your code (using React Hooks as example)
  5. Custom React Hook: When Software Design Meets React Hooks