Multi select from react-select with redux-form not

2020-07-18 11:05发布

So iam using multi select from react-select with redux-form with the onBlur hack(?) which is working fine behind the curtain because when i submit it I have the selected data in values

BUT after visiting any multi select field (even if i dont select anything) I end up with no values at all (nothing is displayed but this
image ))

const options = [
    { value: 'one', label: 'One' },
    { value: 'two', label: 'Two' }
];

<Select
            value="one"
            options={options}
            multi={true}
            {...input}
            onBlur={() => {
              input.onBlur({...input.value})
            }
          }
        />

So i end up with values in the redux state but I cant see any values in the field. Anyone know why is this happening?

2条回答
Explosion°爆炸
2楼-- · 2020-07-18 11:49

Here's example how to make it works. react-select (1.0.0-rc.2), redux-form (5.3.4)

SelectInput.js

import React from 'react';
import Select from 'react-select';
import 'react-select/dist/react-select.css';

export default (props) => (
  <Select
    {...props}
    value={props.input.value}
    onChange={(value) => props.input.onChange(value)}
    onBlur={() => props.input.onBlur(props.input.value)}
    options={props.options}
  />
);

MyAwesomeComponent.js

import React, {PureComponent} from 'react';
import SelectInput from './SelectInput.js';

class MyAwesomeComponent extends PureComponent {
  render() {
    const options = [
      {'label': 'Germany', 'value': 'DE'},
      {'label': 'Russian Federation', 'value': 'RU'},
      {'label': 'United States', 'value': 'US'}
    ];
  return (
    <Field
      name='countries'
      options={options}
      component={SelectInput}
      multi
    />
  )
};
查看更多
别忘想泡老子
3楼-- · 2020-07-18 12:01

I have not used more modern versions of react-select, but a year ago, there were some issues with having to split() the string value by the delimiter to get the values as an array, and then join() them again to give to the component.

Stuff like this:

if (multi) {
  selectValue = value ? value.join(delimiter) : ''
} else {
  selectValue = value || null
}

I recommend examining exactly what the value is in Redux, using Redux DevTools, and what value prop is getting passed to react-select. I'm sure you'll find the problem in there.

查看更多
登录 后发表回答