问题
I have a very simple React application with just one select control. See working application here. The select control has 3 values: Sunday, Monday and Tuesday. Sunday is the default value. Unfortunately on IE11 and Microsoft Edge, the select control gets stuck on the selected value even after a browser refresh! For example, select Tuesday and then refresh the browser - the select box does not return to Sunday, it gets stuck on Tuesday! On Chrome and Safari, I don't see this issue. (Note: You will have to download and run the app on various browsers.)
The code for the main component is shown below. Any idea why IE and Edge are misbehaving?
import React from 'react';
class HelloWorld extends React.Component {
constructor() {
super();
this.state = {
selectedOption: 'sun'
}
}
render() {
let options = [
{ value: 'sun', label: 'Sunday' },
{ value: 'mon', label: 'Monday' },
{ value: 'tue', label: 'Tuesday' }
];
return (
<select
className="form-control"
value={this.state.selectedOption}
onChange={ e => this.setState({selectedOption: e.target.value}) }>
{
options.map(option => {
return <option value={option.value} key={option.value}>{option.label}</option>;
})
}
</select>
);
}
}
export default HelloWorld;
回答1:
Naresh, your code is fine.
Internet Explorer and Edge are misbehaving because they are caching the select tag. On Windows, hit the Ctrl+F5 shortcut to hard refresh. On Mac, hold down ⌘ Cmd and ⇧ Shift key and then press R.
回答2:
From the docs:
If you want to initialize the component with a non-empty value, you can supply a defaultValue prop. For example:
render: function() {
return <input type="text" defaultValue="Hello!" />;
}
Likewise, <input type="checkbox">
and <input type="radio">
support defaultChecked
, and <select>
supports defaultValue
.
https://facebook.github.io/react/docs/forms.html#default-value
来源:https://stackoverflow.com/questions/39737602/select-control-created-in-react-does-not-reset-on-browser-refresh-ie11-and-edge