简体   繁体   中英

React, useState - Why can not retrieve the state value when passing as (props) but can when passing ({props})?

Same as title! Why can not retrieve the state value when passing as (props) but can when passing ({props})?

Code example:

import React, { useState } from 'react'

const Header = (props) => {
  return (
    <div>
      <h1>{props.text}</h1>
    </div>
  )
}

const Button = (props) => (
  <button onClick={props.handleClick}>
    {props.text}
  </button>
)

const Statistic = props => ( <div><h2>{props.text}</h2></div>)

const Statistics = ({props}) =>{
  const total = props.good + props.neutral + props.bad

  console.log("total", total)

  return(
    <div></div>
  )
}

const App = () => {
  // save clicks of each button to its own state
  const [clicks, setClicks] = useState({
    good: 0, neutral: 0, bad: 0
  })

  const setClickToValue= newValue => {
    setClicks(newValue)
  }



  return (
    <div>
      <Header text="Give feedback" />
      <Button handleClick={ () => setClickToValue(clicks.good + 1) } text="Good" />
      <Button handleClick={ () => setClickToValue(clicks.neutral + 1) } text="Neutral" />
      <Button handleClick={ () => setClickToValue(clicks.bad + 1) } text="Bad" />

      <Statistic text="Statistics" />
      <Statistics props={clicks} />
    </div>
  )
}

export default App

I lost an hour to figure out that passing as ({props}) was the correct way. But I still do not understand whats happening, could someone kindly elaborate?

Thanks folks!

the reason is because you have a prop call props. <Statistics props={clicks} />

so the son component gets this as props

props = {
  props: clicks
}

so when you use it like this

const comp = props => {
  props.good
}

it breaks or so because props only have prop call props

what you have to do is some like

<Statistics {...clicks} />

now at yow Statistics component you'll get them props correct

const Statistics = props => {
  console.log(props) // {good: 0, neutral: 0, bad: 0}

}

Thats because react functional component has default argument called props that is an object. To access the the props object we can access by . or [] notation for eg., props.name and javascript also as functionality called object destruction suppose i have object

let obj = {a:123,b:1243}
// i can directly access the object property by destructuring
 let {a} = obj;
 console.log(a)
//output 123

take look at destructuring --->

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