Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

javascript - Material UI Select Component- A component is changing a controlled input of type text to be uncontrolled

I am trying to change the value of Select input and then i am getting the following warning in the console.

index.js:1446 Warning: 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.

But i am updating the state in correct way only , Here is my code

 <Select
        value={props.selectedService}
        onChange={props.handleSelectChange}
        inputProps={{
          name: 'selectedService',            
        }}
   >
   <MenuItem value="">
     <em>None</em>
   </MenuItem>
   <MenuItem value="Dry Cleaning">Dry Cleaning</MenuItem>
   <MenuItem value="Washing and Ironing">Washing and Ironing</MenuItem>
   <MenuItem value="Rolling">Rolling</MenuItem>
 </Select>

And the handleselectchange functionality is here .

handleSelectChange = ({target: {name,value}}) => { 
  console.log(name);
  console.log(value); 
  this.setState({ 
    serviceRequest: { 
      selectedService: value 
    } 
  }); 
}

And state object declaration is below

state = {
    open: false,
    selectedDate: new Date(),
    selectedTime : new Date(),
    mailDetails :{
      name:"",
      email:'',
      message:''
    },
    serviceRequest: {
      name: '',
      email: '',
      mobileNumber:'',
      address:'',
      landMark:'',
      selectedService:''
  }
};

Can anyone please suggest what is the issue?

question from:https://stackoverflow.com/questions/55429442/material-ui-select-component-a-component-is-changing-a-controlled-input-of-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Uncontrolled here means you may be setting the value of the Select component to undefined, this is because value={props.selectedValue} here. In this the props or selectedValue may come null so it turns out to be a uncontrolled component in that.

To solve the warning you can add condition to check null and set default value.

value={props.selectedValue ? props.selectedValue : " "}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...