简体   繁体   English

将状态/自定义钩子传递给另一个自定义 React 钩子是一个好习惯吗?

[英]Is it a good practice to pass state/custom hook into another custom React hook?

So what I'm asking is...所以我要问的是...

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>
}

As far as I understand this should be alright so far.据我了解,到目前为止应该没问题。 See also: https://reactjs.org/docs/hooks-custom.html#tip-pass-information-between-hooks .另请参阅: https://reactjs.org/docs/hooks-custom.html#tip-pass-information-between-hooks But what if things get a little more complex and I start to pass a whole hook into another hook?但是如果事情变得更复杂一点,我开始将整个钩子传递给另一个钩子怎么办?

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";
}

Both car and factory have their own state(s), handlers, methods, maybe even useEffect s and they can be passed into a presentational component. car 和 factory 都有自己的状态、处理程序、方法,甚至可能是useEffect ,它们可以传递到一个展示组件中。 I haven't found any critique of this so far, so I assume it should be alright, but my intuition tells me that it can lead to some unexpected behaviour (For example, if factory starts to change the state of the car).到目前为止我还没有发现任何对此的批评,所以我认为它应该没问题,但我的直觉告诉我它可能会导致一些意想不到的行为(例如,如果工厂开始更改汽车的 state)。

There will be no problem because you use your custom hooks in the topmost level, so they are executed every time when the state of the component change.不会有问题,因为您在最顶层使用自定义挂钩,因此每次组件的 state 更改时都会执行它们。
Just handle the logic in the hooks carefully.只需小心处理钩子中的逻辑即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM