提交带有 initialValues 的未修改的 redux-form 将 react-select 值转换为 null 数组

Submitting untouched redux-form with initialValues converts react-select values to array of null

我正在使用本指南将 react-selectredux-form 集成:https://gist.github.com/leocristofani/98312e61807db8f32e720c9f97a186e5

import React, { PropTypes } from 'react';
import Select from 'react-select';
import 'react-select/dist/react-select.css';

RFReactSelect.defaultProps = {
  multi: false,
  className: ""
};

RFReactSelect.propTypes = {
  input: PropTypes.shape({
    name: PropTypes.string.isRequired,
    value: PropTypes.string.isRequired,
    onBlur: PropTypes.func.isRequired,
    onChange: PropTypes.func.isRequired,
    onFocus: PropTypes.func.isRequired,
  }).isRequired,
  options: PropTypes.array.isRequired,
  multi: PropTypes.bool,
  className: PropTypes.string
};

export default function RFReactSelect({ input , options, multi, className }) {
  const { name, value, onBlur, onChange, onFocus } = input;
  const transformedValue = transformValue(value, options, multi);
  return (
    <Select
      valueKey="value"
      name={name}
      value={transformedValue}
      multi={multi}
      options={options}
      onChange={multi
        ? multiChangeHandler(onChange)
        : singleChangeHandler(onChange)
      }
      onBlur={() => onBlur(value)}
      onFocus={onFocus}
      className={className}
    />
  );
}

/**
 * onChange from Redux Form Field has to be called explicity.
 */
function singleChangeHandler(func) {
  return function handleSingleChange(value) {
    func(value ? value.value : '');
  };
}

/**
 * onBlur from Redux Form Field has to be called explicity.
 */
function multiChangeHandler(func) {
  return function handleMultiHandler(values) {
    func(values.map(value => value.value));
  };
}

/**
 * For single select, Redux Form keeps the value as a string, while React Select 
 * wants the value in the form { value: "grape", label: "Grape" }
 * 
 * * For multi select, Redux Form keeps the value as array of strings, while React Select 
 * wants the array of values in the form [{ value: "grape", label: "Grape" }]
 */
function transformValue(value, options, multi) {
  if (multi && typeof value === 'string') return [];

  const filteredOptions = options.filter(option => {
    return multi 
      ? value.indexOf(option.value) !== -1
      : option.value === value;
  });

  return multi ? filteredOptions : filteredOptions[0];
}

虽然有一个问题(到目前为止),但它仍然有效。

当我设置表单的 initialValues 并在不触及 react-select 组件的情况下提交它时,它将 select 的初始值从 ["id1", "id2", "id3"] 转换为 [空,空,空]。

没关系。经过一个月的努力,终于能够从头开始解决它。作为 React 的新手,有很多活动部件我不得不检查但没有检查。