Tell me how to correctly write the values ​​in this.state from this.props before rendering the component, I run this.props to for in and write them in this.state so that when rendering, the data from this.props are displayed in the component, everything works but issues warning in the console Uncontrolled Components do not throw a link to the docks, already watched.

constructor(props) { super(props); this.state = { name: '', surname: '', email: '', phone: '' } } componentDidMount() { for(let key in this.props){ if(this.props[key] != this.state[key]){ this.setState({[key]: this.props[key]}); } } } 
  • do it in the constructor - xFloooo
  • Yes, and why in the state loop update? collect the entire object and completely change the state ... - xFloooo

1 answer 1

To begin with, you don't need componentDidMount , all this can be initialized in the constructor quite elementary:

 constructor(props) { super(props); this.state = { name: '', surname: '', email: '', phone: '', ...props } } 

Secondly, it does not bother you to foresee the case of changing properties from outside in componentWillReceiveProps

 componentWillReceiveProps(nextProps) { const props = {}; for (let key in nextProps) { if (nextProps[key] != this.state[key]) { props[key] = nextProps[key]; } this.setState(props); } 

Thirdly, it is not clear why to store the same data in two places, which props do not suit you? Placing the data in the state you a) duplicate them, b) potentially force the component to be redrawn twice (in the case of changing properties)