【问题标题】:Is it a good practice to pass state/custom hook into another custom React hook?将状态/自定义钩子传递给另一个自定义 React 钩子是一个好习惯吗?
【发布时间】:2021-06-02 03:08:03
【问题描述】:

所以我要问的是......

const useCustomHook = color => {
  const rainbowColors = ["red", "yellow", "blue", "purple"];
  const makeARainbow = rainbowColors.indexOf(color) != -1;
  return { makeARainbow };
}

const Component = () => {
  const [color, setColor] = useState("green");
  const magicobject = useCustomHook(color);
  return <div>{magicobject.makeARainbow ? "Hurray!" : "Nah"}</div>
}

据我所知,到目前为止应该没问题。另请参阅:https://reactjs.org/docs/hooks-custom.html#tip-pass-information-between-hooks。但是如果事情变得更复杂一些,我开始将整个钩子传递给另一个钩子怎么办?

const useFactory = car => {
  const [availableFrames, setAvailableFrames] = useState([]);
  const [engines, setEngines] = useState([]);
  ...
  const readyForProduction =  availableFrames.indexOf(car.frame) != -1 && engines.map(e => e.type).indexOf(car.engineType) != -1 ...;
  return { readyForProduction, ... }
}

const Component = () => {
  const car = useCarModel();
  const factory = useFactory(car);
  return factory.readyForProduction ? "Hurray!" : "Nah";
}

汽车和工厂都有自己的状态、处理程序、方法,甚至可能是useEffects,它们可以传递到一个展示组件中。到目前为止我还没有发现任何对此的批评,所以我认为它应该没问题,但我的直觉告诉我它可能会导致一些意想不到的行为(例如,如果工厂开始改变汽车的状态)。

【问题讨论】:

    标签: javascript reactjs react-hooks use-state


    【解决方案1】:

    不会有问题,因为您在最顶层使用自定义挂钩,因此每次组件状态发生变化时都会执行它们。
    只需小心处理钩子中的逻辑即可。

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 1970-01-01
      • 2021-01-31
      • 2019-04-22
      • 2022-10-09
      • 1970-01-01
      • 2020-12-25
      • 2021-11-05
      • 1970-01-01
      相关资源
      最近更新 更多