【问题标题】:React-select option not getting selected反应选择选项没有被选中
【发布时间】:2018-06-09 15:45:15
【问题描述】:

我正在使用react-select 包。当我选择下拉选项时,我的 onChange 操作正常工作并更新状态。但是该选项没有被选中。意思是,它不显示映射到状态的值,而只是默认占位符。

我想我错过了一些小东西,但我对 react 和 redux 有一些新的东西,我不确定这可能是什么。提前感谢您的帮助:)

正文.js

<Select id="input-field" value={this.props.create.selectedOption} onChange={this.props.addOption}
   options={[
      { value: 'navigate', label: 'Navigate to <URL>' },
      { value: 'enter', label: 'I enter <InputValue> to the <ElementKey>' },
      { value: 'click', label: 'Click on <ElementKey>' },
      ]}
/>


const mapStateToProps = (state, ownProps) => {
    return {
        create: state.reducerCreate
    }
}

Reducer.js

const initialState = {
    feature: '',
    scenarios: [],
    activeIndex: '',
    selectedOption: ''
}

【问题讨论】:

  • 你的 redux 商店更新了吗?如果你使用state而不是props控制&lt;Select&gt;组件会更好
  • 是的,商店正在更新@Dane
  • 那么 this.props.create.selectedOption 可能是 undefined ?就像我说的,最好使用this.state 来管理Select 组件,因为它只会重新渲染,而不是更改props

标签: javascript reactjs redux react-select


【解决方案1】:

回答我自己的问题,我发现仅传递选定的选项标签/值是不够的,我们需要传递整个对象;

{ value: 'navigate', label: 'Navigate to <URL>' }

然后我们将 select 标签的 value 属性映射到 state 的值。

更新Body.js

<Select id="input-field" componentClass="select" value={this.props.create.selectedOption.value} onChange={this.props.addOption}


const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        addOption: (option) => {
            console.log(option)
            dispatch(addOption(option))
        }
    };
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    相关资源
    最近更新 更多