简体   繁体   中英

Cleaner way to pass state variables and methods to child components in React?

Beginner to React, I have multiple state variables:

function ParentComp(){
      const [firstName, setFirstName] = useState("")
      const [lastName, setLastName] = useState("")
      const [address, setAddress] = useState("")

      return <p>Bonjour</p>
}

Of course I can pass them to the child components like this:

<ChildComponent firstName = {firstName} setFirstName = {setFirstName}
                lastName = {lastName} setLastName = {setLastName}
                address = {address} setAddress = {setAddress}/>

But I have many more state variables, and actually I want to pass them to the child of the ChildComponent. Is there a way to wrap them in a array or object somehow? I googled and found "context api" but I'd like a more beginner friendly solution.

You can do something like this if you want to keep them as separate states

<ChildComponent {
  ...{
      firstName, 
      lastName, 
      address, 
      setFirstName, 
      setLastName, 
      setAddress
   }
} />

Otherwise, you coud use useReducer for easier updates to the state and you will get a single object with all states and one update action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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