14

我正在尝试使用 redux 制作一个异步反应选择组件,但不知何故无法在下拉列表中获得搜索结果。对此非常陌生。请帮忙 :)

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 的下拉列表中。

4

1 回答 1

5

试试这个,我们也可以从 action 中返回,但它打破了 reducer 的整个想法。

// 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>
    );
  }
}
于 2018-11-21T18:59:50.710 回答