简体   繁体   中英

How do I rerender form value and state value when using hooks and state is changed in a different component in react

I have an app that updates state in a child component with the function setBrewLog that was set with useState

const [brewLog, setBrewLog] = useState([{ og: '' }]) .

In the react-dev tools I can see that state is updated, and inside useEffect I can see that the component is rerendered, but the form field will not update. As well On a side note does Formik solve this issue?

I do get a error in the Chrome console.

A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

Here is a simplified version of my code.

export const Brewlog = () => {
  const [brewLog, setBrewLog] = useState({ og: '' })

  const onBrewLogChanged = e => {
    const tempBrewLog = [...brewLog]
    
    tempBrewLog[e.target.id[e.target.id.length - 1]][e.target.name] = e.target.value
    setBrewLog(tempBrewLog)
  }
  // useEffect is triggered when the Child component updates state.
  useEffect(() => {
    console.log(brewLog)
  })
  return(
   <> 
    <h3>Brewlog</h3>
    <Child setBrewLog={setBrewLog} />
          <label htmlFor='og' >Original gravity</label>
           //Does not update on state change
          <p> is:{brewLog.og}</p>
          <input 
            type="text" 
            name='og'
            id='og0'
            //does not update on state change 
            placeholder={brewLog.og} 
            value={brewLog.og}
            onChange={onBrewLogChanged}
          />
    <button type="button" onClick={''} >
      Save Recipe
    </button>
  </>
  )
}

const Child = ( props ) => {
  const [message, setMessage] = useState('')
  
  const ChangeState = () => {
    props.setBrewLog([{ og: '1' }])
     setMessage('OG is 1')
    },
    
  return (
    <div>
      <button type='button' onClick={ChangeState}>Start</button>
      <p>{message}</p>
    </div>
  )
}
export default Child

Thanks you for your insights

As Emilie Bergeron pointed out I was using two different structures for my state. Changing them both to an object solved the 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