简体   繁体   中英

Why doesn't this select list render with the correct item selected based on the defaultValue

I have a ReactJS component:

var RegionsList = React.createClass({

    handleChange: function () {
        var regionId = this.refs.userRegions.getDOMNode().value;
        this.props.onRegionSelected(regionId);
    },

    componentDidMount: function() {
        $.get("/translation/activeuserregions", function(result) {
            if(this.isMounted()) {
                this.setState({
                    selectedRegionId: result.SelectedRegionId,
                    regions: result.Regions
                })
            }     
        }.bind(this));
    },

    getInitialState: function(props) {
        return {
            selectedRegionId: '',
            regions: []    
        }    
    },

    render: function() {
        return (
            <div id="RegionsListForm" className="navbar-form navbar-left regions-list">
                <div className="input-group navbar-searchbox">
                    <span className="input-group-addon">
                        <span>Region</span>
                    </span>
                    <select ref="userRegions" onChange={this.handleChange} defaultValue={this.state.selectedRegionId} className="form-control valid" id="region" name="region" aria-invalid="false">
                        {this.state.regions.map(function(region) {
                            return <option key={region.Id} value={region.Id} label={region.RegionName}>{region.RegionName}</option>        
                        })}                                             
                    </select>
                </div>
            </div>
        );
    },


})

It appears to work correctly. But initially it does not render with the correct item selected. Although the defaultValue appears to be set correctly so I don't understand why.

What am I doing wrong?

When the <select> is initially mounted, the default value is '' . Once an uncontrolled form component is in the DOM, React doesn't look updates to the defaultValue prop. In this case it looks like your intention is to always have the selectedRegionId state match what's shown to the user, so you may want to change defaultValue to value and add a this.setState({selectedRegionId: regionId}); call to your onChange handler; then your component state and the DOM will always be in sync.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM