如何在反应中分年?

时间:2019-03-28 09:53:22

标签: reactjs

我用react-hook编写了代码,我的代码很大。如何正确划分我的代码。我知道有两种方法可以做到,但不确定哪种更好。哪种方法更好,如果您知道另一种方法,则提示并解释优势。我将举一个小例子。code first way second way

代码

const App = () => {
  const [count, setCount] = useState(0);

  return (
    <section className="counter">
      <h1>Счётчик: {count}</h1>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(0)}>Обнулить</button>
      <button onClick={() => setCount(count + 1)}>+</button>
    </section>
  );
};

第一种方式

export const useCounter = (initialState = 0, step = 1) => {
  const [count, setCount] = useState(initialState);

  const _decrement = () => setCount(prevCount => prevCount - step);
  const _reset = () => setCount(0);
  const _increment = () => setCount(prevCount => prevCount + step);

  return {
    count,
    _increment,
    _decrement,
    _reset
  };
};

第二种方式

const UseCounter = ({ value, setValue }) => {
  return (
    <section className="counter">
      <h1>Счётчик: {value}</h1>
      <button onClick={() => setValue(value - 1)}>-</button>
      <button onClick={() => setValue(0)}>Обнулить</button>
      <button onClick={() => setValue(value + 1)}>+</button>
    </section>
  );
};

0 个答案:

没有答案