简体   繁体   English

将 Hook 传递给孙子/多个组件

[英]Passing Hook down to grandchild/multiple components

I'm wondering If I can pass a hook down multiple components.我想知道我是否可以将一个挂钩传递给多个组件。 For example in my parent component I declare a hook and I pass the hook components into the child.例如,在我的父组件中,我声明了一个挂钩并将挂钩组件传递给子组件。 And within that child I pass that hook into the grandchild and within the grandchild I set the state for the hook.在那个孩子中,我将钩子传递给孙子,在孙子中,我将 state 设置为钩子。 I know that I can pass hooks from parent to child but unsure if I can do it for multiple components.我知道我可以将钩子从父级传递给子级,但不确定是否可以为多个组件执行此操作。

export const Parent = () => {
  const [data, setData] = useState("")

  return(
      <Child data={data}, setData={setData}
   )

export const Child = ({data,setData}) => 
  return(
      <GrandChild data={data}, setData={setData}
  )

export const GrandChild = ({data,setData}) => 
  setData("hi")
  return(
      <div>{data}</div>
  )

You can do this as many times as you want but there are better ways to do this like Redux or Context API.您可以根据需要多次执行此操作,但有更好的方法来执行此操作,例如 Redux 或上下文 API。 These tools are for preventing these kind of redundant actions.这些工具用于防止此类冗余操作。

This can get messy very quickly as apps grow and can cause issues finding bugs and errors.随着应用程序的增长,这会很快变得混乱,并可能导致发现错误和错误的问题。 It is known as prop drilling.它被称为支柱钻孔。 I would strongly recommend the following documentation on useContext我强烈推荐以下关于useContext的文档

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

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