Select box not changing after changing the value from redux-devtools

最后都变了- 提交于 2020-01-04 07:31:07

问题


locale is in my redux app state. Changing its value through react-devtools (revert option), changes paragraph inner value but not the select box value. If it renders again shouldn't it take the same value as inside the p tag?

import React, {Component, PropTypes} from 'react'
import {defineMessages, injectIntl, intlShape} from 'react-intl'
const messages = defineMessages({
  spanish: {
    id: 'languageSelector.spanish',
    description: 'Select language',
    defaultMessage: 'Spanish'
  },
  english: {
    id: 'languageSelector.english',
    description: 'Select language',
    defaultMessage: 'English'
  },
  french: {
    id: 'languageSelector.french',
    description: 'Select language',
    defaultMessage: 'French'
  }
})

class LanguageSelector extends Component {
    render () {
      const {formatMessage, locale} = this.props.intl
      return (
        <div>
        <select defaultValue={locale} onChange={(e) => this.handleChange(e)}>
                <option id='es' value='es'>{formatMessage(messages.spanish)}</option>
                <option id='fr' value='fr'>{formatMessage(messages.french)}</option>
                <option id='en' value='en'>{formatMessage(messages.english)}</option>
        </select>
        <p>{locale}</p>
        </div>
        )
    }
    handleChange (e) {
      this.props.onChange(e.target.value)
    }
}

LanguageSelector.propTypes = {
  intl: intlShape.isRequired,
  onChange: PropTypes.func.isRequired
}
export default injectIntl(LanguageSelector)

回答1:


Change defaultValue to value. i.e.

<select value={locale} onChange={(e) => this.handleChange(e)}>

Explanation

You only use defaultValue when the form field is an uncontrolled component. The only way to change the value of an uncontrolled component is through user input.

If you use value then the form component is considered a controlled component. Its value can be changed in subsequent renders by setting the value explicitly. Controlled components must also have an onChange handler, which yours does.

For more information on controlled/uncontrolled form components, see Forms in React.



来源:https://stackoverflow.com/questions/35011730/select-box-not-changing-after-changing-the-value-from-redux-devtools

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