反应关联(反应选择)

时间:2017-10-04 15:13:15

标签: javascript reactjs redux react-select

我想知道如何在React中建立关联(就像在Rails中一样)。我希望一家公司有多个联系人,一个联系人属于一家公司。 我有两个单独的模型,联系公司,当我创建联系人时,我想选择公司它属于哪里。

我在考虑使用react-select,其中下拉菜单将从数据库中获取所有公司名称。

我有actions/index.js我得到了所有公司:

export const fetchCompanies = () => async dispatch => {
  const res = await axios.get('/api/companies');

    dispatch({type: FETCH_COMPANIES, payload: res.data.companies })
}

我将其导入components/CompanyNew.js并尝试制作下拉菜单。 (我从另一个文件导入formFieldContactField)。如果我根据文档放置一些虚拟数据,它会正确显示。这是我的代码:

import { fetchCompanies } from '../../actions';
var Select = require('react-select');

class ContactNew extends Component {
    componentDidMount() {
            this.props.fetchCompanies();
    }

    const getOptions = (input) => {
      return this.props.fetchCompanies()
        .then((response) => {
          return response.json();
        }).then((json) => {
          return { options: json };
        });
    }


    renderFields() {
        return _.map(formField, ({ label, name }) => (
            <Field
                key={name}
                component={ContactField}
                type="text"
                label={label}
                name={name}
            />
        ));
    }
    onSubmit(values) {
        this.props.createContact(values, () => {
            this.props.history.push('/');
        });
    }

    render() {
        const { handleSubmit } = this.props;
        return (
            <div>
                <h3>Add new contact:</h3>
                <Form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
                    {this.renderFields()}
                    <Select.Async
                        name="form-field-name"
                        loadOptions={this.getOptions()}
                    />
                    <button type="submit">Save</button>
                </Form>
            </div>
        );
    }
}


export default reduxForm({
    form: 'contactForm',
    destroyOnUnmount: false
})(connect(null, { createContact })(ContactNew));

在Rails中,这很容易做到,但我不知道如何在React中做到这一点,因为我尝试过的是无效。

1 个答案:

答案 0 :(得分:0)

我注意到的两件事,

首先:您似乎期望从行动返回值

export const fetchCompanies = () => async dispatch => {
  const res = await axios.get('/api/companies');

  dispatch({type: FETCH_COMPANIES, payload: res.data.companies });
  return res; // missing return
}

第二:我认为你需要将一个函数传递给Select.Async组件而不是一个承诺this.getOptions vs this.getOptions()

<Select.Async
  name="form-field-name"
  loadOptions={this.getOptions}
/>

不确定这些是否会导致您描述的问题,但可能需要从那里开始