簡體   English   中英

將狀態/自定義鈎子傳遞給另一個自定義 React 鈎子是一個好習慣嗎?

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

所以我要問的是...

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

car 和 factory 都有自己的狀態、處理程序、方法,甚至可能是useEffect ,它們可以傳遞到一個展示組件中。 到目前為止我還沒有發現任何對此的批評,所以我認為它應該沒問題,但我的直覺告訴我它可能會導致一些意想不到的行為(例如,如果工廠開始更改汽車的 state)。

不會有問題,因為您在最頂層使用自定義掛鈎,因此每次組件的 state 更改時都會執行它們。
只需小心處理鈎子中的邏輯即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM