gpt4 book ai didi

redux - 带有 redux 的异步 React-select

转载 作者:行者123 更新时间:2023-12-01 22:18:33 26 4
gpt4 key购买 nike

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

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 存储中正确更新,但没有反射(reflect)在选择异步的下拉列表中。

最佳答案

试试这个,我们也可以从操作中返回,但它破坏了 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>
);
}
}

关于redux - 带有 redux 的异步 React-select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44109366/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com