简体   繁体   中英

Passing updated state from parent to child

I create a let variable in my parent component with the boolean false. I pass that variable as a prop to the child component. I change the variable to true through a function in the parent component. My problem is that the value of the prop in the child component is still false when I console.log it afterwards.

Parent:

function App() {
 
  let success = false
  
 
  const changePW = async ({password, repeatPW}) => {


    success = true
    console.log(`Success App0: ${success}`)
    console.log('ChangePW')

  return (
    <BrowserRouter>
    <div className="container">
      <Header/>
      <Route path='/' exact render={(props) => (
        <>
          <AddPasswort onChange = {changePW} success = {success}/>
          <Footer />
        </>
       )}/>
       
      <Route path='/about' component={About} />
      
      <Route path='/success' component={Success} />
      <Route path='/error' component={Error} />
      
      
      </div>
    </BrowserRouter>
  
  );
}

export default App;

Child

const AddPasswort = ({onChange,success}) => {
    const[password, setPassword] = useState('')
    const[repeatPW, setRepeatPW] = useState('')
    
    // create a history object 
    const history = useHistory()  
   

    const onSubmit = async (e) => {
        e.preventDefault();

     
            await onChange({password, repeatPW})
            console.log(success)
            // navigate to the success page 
            if (success){
                console.log('success')
                history.push("/success")
            }
            else{
                console.log('error')
                history.push("/error")
            }    
        }


    }
    ...
   
}

export default withRouter(AddPasswort);

I thought the problem was that the function does not wait for onChange to finish so I made it asynch, but that did not resolve the issue

because success is not a state, only changing state will re-render component. try

const [success, setSuccess] = useState(false);

to change the value of success to true, do

setState(true)

this should solve your problem

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