【问题标题】:How do I populate Select Options from Redux store?如何从 Redux 商店填充 Select Options?
【发布时间】:2021-07-05 01:44:05
【问题描述】:

我正在使用 react-select

我有一个创建新联系人的表单。在我的 redux 商店中,我已经创建了组。当我单击 Select 以显示选项时,我想从我的 redux 存储中加载选项。

redux store 中的“groups”只有一个值,即后端 GroupModel 中的 title: String。

我了解 react-select 需要有 label: '', value: ''

如果我自己创建一个数组并传递其中的值就可以了。但是使用 redux 没有任何效果。我在网上任何地方都找不到任何对我来说似乎微不足道的答案....

下面是我的组件

import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import PropTypes from 'prop-types';
import Select from 'react-select';
import { createContact } from '../../actions/index';
import { Button, Form, FormGroup, Input, Label } from 'reactstrap';
import Divider from '../common/Divider';

const ContactForm = ({ hasLabel }) => {
  const dispatch = useDispatch()

  // State
  const [contact, setContact] = useState({ 
    group: '',
})
  
  // Submit Handler
   const handleSubmit = e => {
    e.preventDefault()
    dispatch(createContact(contact))
   };

  // Change Handler
  const handleChange = e => {
    setContact({...contact, [e.target.name]: e.target.value})
  };
  
  // bringing in our state from redux
  const groups = useSelector((state) => state.groups)
  

  return ( 
  <>
    <Form onSubmit={handleSubmit}>
      <div>
        <FormGroup>
        <Label>
          Choose Group/List</Label>
            <Select
              name="group"
              options={groups}
              getOptionlabel={({title}) => title}
              getOptionValue={({_id}) => _id }
              onChange={() => {}}
              isMulti
            />
        </FormGroup>
      </div>
    </Form>
  </>
  );
};

ContactForm.propTypes = {
  
  hasLabel: PropTypes.bool
};

ContactForm.defaultProps = {
  layout: 'basic',
  hasLabel: false
};

export default ContactForm;

【问题讨论】:

    标签: reactjs redux react-select


    【解决方案1】:

    好的....所以我上面的解决方案非常正确。我遇到的问题是 getOptionlabel 需要成为 getOptionLabel

    我希望需要在 redux 中使用 react-select 的人找到这篇文章,它会有所帮助。

    所以基本上只需使用 useSelector 或 connect 引入你的 redux 状态, 然后确保在您的 Select 组件中使用下面的道具

    getOptionLabel={({title}) => title}
    getOptionValue={({_id}) => _id}
    
    

    【讨论】:

      猜你喜欢
      • 2016-07-14
      • 2018-11-30
      • 2021-02-06
      • 1970-01-01
      • 2020-03-26
      • 2016-04-01
      • 2014-02-11
      • 2018-06-18
      • 2019-07-14
      相关资源
      最近更新 更多