关注分离,合理复用
- 展示组件(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 (
); };
<button onClick={onClickMinus} className="button">
-
</button>
<div className="number">{value}</div>
<button onClick={onClickPlus} className="button">
+
</button>
<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 }; }; ```