Select control created in React does not reset on browser refresh (IE11 and Edge)

☆樱花仙子☆ 提交于 2020-02-03 07:32:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!