Multi select from react-select with redux-form not working as intended

元气小坏坏 提交于 2020-02-01 05:46:25

问题


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

))
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?


回答1:


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.




回答2:


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
    />
  )
};


来源:https://stackoverflow.com/questions/41085321/multi-select-from-react-select-with-redux-form-not-working-as-intended

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