我试图用数据库中的数据填充选择框,但尝试这样做时,出现以下错误消息:
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `Event`.
这是我的代码:
import Select from 'react-select';
class Event extends Component {
...
render() {
const getOptions = () => {
return axios
.get("/api/categories") // [{_id: "", name: "", user: ""... }, ...]
.then(function (res) {
//res.data.map(el => ({ label: el.name, value: el._id }))
let options = res.data.map( cat => ({ value: cat._id, label: cat.name }));
return { options };
});
};
return (
...
<Select.Async
autoload={true}
loadOptions={getOptions} />
...
我发现this page带有一些实现它的示例,但仍然无法摆脱错误。
答案 0 :(得分:0)
您链接的示例已经很老了,在async
内进行render
的调用听起来并不好,这是我如何使用react-select
渲染一堆东西的示例从我的数据库中
import React from "react";
import Select from "react-select";
import "react-select/dist/react-select.css";
import PropTypes from 'prop-types';
export const styles = {
flex: {
flexGrow: 1
}
};
export class Options extends React.Component {
state = {
selectedOption: "BTC"
};
componentDidMount() {
// We make our API calls here
this.props.getTickers();
this.props.setOption("BTC");
}
handleChange = selectedOption => {
this.setState({selectedOption: selectedOption.value}, () => {
this.props.setOption(this.state.selectedOption);
});
};
formatOptions = (options = []) => {
return options.map(option => {
return {value: option.symbol, label: option.name};
});
};
render() {
const {options, classes} = this.props;
const {selectedOption} = this.state;
if (options === null) {
return <p>Loading....</p>
} else {
return (
<Select
className={classes.flex}
name="Search Currency"
value={selectedOption}
onChange={this.handleChange}
options={this.formatOptions(options)}
clearable={false}
/>
);
}
}
}
Options.propTypes = {
getTickers : PropTypes.func,
setOption : PropTypes.func,
options : PropTypes.array,
classes : PropTypes.object
};
Options.defaultProps = {
options : [],
classes : {},
getTickers: () => {},
setOption : () => {}
};
export default Options;