React a component is changing an uncontrolled input of type checkbox to be controlled

后端 未结 3 2254
眼角桃花
眼角桃花 2021-02-19 06:33

react gives me a warning: \"A component is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or

3条回答
  •  星月不相逢
    2021-02-19 07:29

    Something worth noting about the above code snippet. When you set a state in the constructor from props, it is always best to set the state to a "controlled" value i.e. a tangible value such as an int, float, string, array, map, etc. The error you are getting is the result of props.value being set to null

    So, Consider setting your constructor state like this:

    this.state = {
        value: props.value ? props.value : 'empty'
    }
    

    What is happening here is it is checking if props.value has a value, if it does it sets the state to props.value, if props.value is null, it sets the state to the string: `'empty'

提交回复
热议问题