skip to Main Content

i’m a rookie in react

the code is:

const Demo = () => {
  const [current, setCurrent] = useState(0)
  const add = () => {
    console.log(current)
    setCurrent(current + 1)
  }
  const Parent = (props) => {
    return props.data.child
  }
  const Child = () => {
    return (
      <div onClick={() => {
        add()
      }}>Child</div>
    )
  }    
  // const data = {
  //   child: <Child></Child>
  // }
  const [data] = useState({
    child: <Child></Child>
  })

  return (
    <div>
      <Parent data={data}>
      </Parent>
    </div>
  )
}

Now the console out is 0 on every click, but when not using useState, the current will increace

I don’t know why, could any one explain for me, thank you so so much

2

Answers


  1. Chosen as BEST ANSWER

    I get it if use

    const data = {
      child: <Child></Child>
    }
    

    Child is new, the current in add function closure is new on every render.

    but if use

    const [data] = useState({
      child: <Child></Child>
    })
    

    Child is the same one in 2nd render, the current in add function closure is the same one, not the new current in 2nd render process.


  2. useState only user for store data, not element. I see do you want to send data from Parent to Child. Try this!

    const Demo = () => {
      const [current, setCurrent] = useState(0);
      const add = () => {
        console.log(current);
        setCurrent(current + 1);
      };
      const Parent = ({ children }) => {
        return <>{children}</>;
      };
      const Child = () => {
        return (
          <div
            onClick={() => {
              add();
            }}
          >
            Child
          </div>
        );
      };
    
      const [data] = useState(0);
    
      return (
        <div>
          <Parent data={data}>
            <Child />
          </Parent>
        </div>
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search