React select 使用 Redux Form 设置初始值

React select set initial value with Redux Form

我正在尝试使用 Redux 表单字段为我的 Select 标签设置一个初始值。

Redux 字段:

<Field
                    name="statusDto.pkid"
                    component={renderSelectField}
                    type="text"
                    isHidden="true"
                    placeholder="Select Status"
                    options={userRegistrationStatus && userRegistrationStatus.map((values) => { return ({ value: values.pkid, label: i18next.languages[0] === 'en' ? values.enName : values.trName }); })}
                  />

Redux 形式:

UserRegistrationForm = reduxForm({
  validate,
  form: 'User_Registration_Form', // a unique identifier for this form
  enableReinitialize: true,
})(UserRegistrationForm));

反应 Select:

handleChange = (selectedOption) => {
    const { onChange } = this.props;
    this.setState({ selectedOptionState: selectedOption });
    onChange(selectedOption.value);
  };

 <Select
        name={name}
        value={selectedOptionState}
        onChange={this.handleChange}
        styles={customStyles}
        options={options}
        clearable={false}
        className="react-select"
        placeholder={placeholder}
        isDisabled={isDisabled}
        classNamePrefix="react-select"
        theme={(theme) => ({
          ...theme,
          borderRadius: 0,
          colors: {
            ...theme.colors,
            primary: '#70bbfd',
          },
        })}
      />

使用redux-form initialize,我尝试将第一个值赋值给react-select,但似乎不值得。你能帮帮我吗?

我解决了问题。

反应 Select:

<Select
        name={name}
        value={(value === '') ? null : options.find(obj => obj.value === value)}
        onChange={this.handleChange}
        styles={customStyles}
        options={options}
        clearable={false}
        className="react-select"
        placeholder={placeholder}
        isDisabled={isDisabled}
        classNamePrefix="react-select"
        theme={(theme) => ({
          ...theme,
          borderRadius: 0,
          colors: {
            ...theme.colors,
            primary: '#70bbfd',
          },
        })}
      />

{label:"LABELX", value: "ValueY"} 初始化你 Select 组件的 redux ReduxForm 字段 在您的 RenderSelectField 组件上添加一个 属性 值,该值应映射到从 props.input

收到的 属性
const RenderSelectField =(props) => {

  // Complete the seleect component with your additional props
  return (
    <Select
      value={props.input.value}
    />
  );
}

因为 valueoptions 数组的一个元素。您不需要编写 find 函数