Async React-select with redux

时间:2017-05-22 09:27:18

标签: redux react-select

我正在尝试使用redux创建异步react-select组件,但不知何故无法在下拉列表中获取搜索结果。对此非常陌生。请帮助:)

import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import Select from 'react-select';

import { fetchInstitutionsIfNeeded } from '../../actions/institutions';

class Signup extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: null
        };
        this.getInstitutions = this.getInstitutions.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    onChange(input) {
        this.setState({
            value: input
        });
    }

    getInstitutions(input) {
        const { dispatch } = this.props;
        if (!input) {
            return Promise.resolve({ options: [] });
        }
        dispatch(fetchInstitutionsIfNeeded(input));
    }

    render() {
        let options = this.props.options;
        return (
            <div>
                <Select.Async
                    name="institute"
                    value={this.state.value}
                    autoload={false}
                    onChange={this.onChange}
                    loadOptions={this.getInstitutions}
                />
            </div>
        );
    }
}

const mapStateToProps = (state) => ({
    options: state.institutions.options
});

export default connect(mapStateToProps)(Signup);

此外,选项对象也已正确格式化,并在redux存储中正确更新,但未反映在select async的下拉列表中。

1 个答案:

答案 0 :(得分:0)

尝试一下,我们也可以从行动中恢复过来,但这打破了减速器的整个想法。

// actions.js
export const getProducts = (input = '') => async (dispatch) => {
  dispatch({
    type: GET_PRODUCTS_PENDING,
    payload: {},
  });
  try {
    const response = await axios.get(`/api/v1/products/`);
    dispatch({
      type: GET_PRODUCTS_SUCCESS,
      payload: response.data,
    });
  } catch (error) {
    // handle errors
  }
};

// components.jsx
class Signup extends PureComponent {
  async getProductsForSelect(input) {
    await this.props.getProducts(input);
    return this.props.product.options;
  }

  render() {
    const { handleSubmit } = this.props;
    return (
      <form onSubmit={handleSubmit}>

        <AsyncSelect
          isMulti
          cacheOptions
          defaultOptions
          loadOptions={(e) => this.getProductsForSelect(e)}
        />

      </form>
    );
  }
}