![](/img/trans.png)
[英]react-select onChange target value undefined error - in nextjs
[英]React-Select onChange to store a value to pass to API call
我正在开发我的第一个网络应用程序并引导这个应用程序,我在更改 API 获取请求的 URL 时遇到问题。 我正在使用 react-select 创建一个下拉菜单,并且我希望下拉选择来改变搜索条件,例如:
我有一个 baseurl.com/
并希望根据下拉选择创建一个变量,将 append 到 baseurl。 我从下拉列表中选择的两个选项是“姓名”和“生日”,如果您使用 select“姓名”,则 URL 将是 baseurl.com/Patient?name= + inputvalue。
如果您是 select '生日',则 URL 将为 baseurl.com/Patient?birthdate=eq + inputvalue
我想保持 baseURL 不变,因为我最终将不得不向 select 添加更多选项。 我已经让 inputvalue 在我的应用程序中工作,所以我相信我不需要对其进行更改。
到目前为止,这是我的一些代码,当我进行选择时,它给了我一个“无法读取未定义的属性‘值’错误”。此外,我还没有制作将 state 存储为变量的组件,但我将在涉及到它时过桥任何见解表示赞赏,谢谢:
const choice = [
{value : "Name", label: "Name" },
{value : "bDay", label: "Birthday (YYYY-MM-DD)"}
];
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: 'Search',
queryResult: {},
criteria: '',
showSVG: false
};
this.handleChange = this.handleChange.bind(this);
this.getInputValue = this.getInputValue.bind(this);
this.baseURL = this.baseURL.bind(this);
}
getInputValue(e) {
this.setState({ inputValue: e.target.value });
}
handleChange(e) {
this.setState({criteria: e.target.value});
console.log(e.target.value);
}
baseURL(e) {
const url = 'https://baseURL.com/';
[BLOCK FOR FETCH REQUEST]
render() {
return (
<div className="input-wrapper">
{/* ON CHANGE SELECT */}
<Select options={choice} value={this.state.criteria} onChange={this.handleChange} />
<input
type="text"
value= {this.state.inputValue}
onFocus = {() => this.setState({ inputValue: '' })}
onChange={this.getInputValue}
onKeyDown={this.baseURL} />
<img className={this.state.showSVG ? "isVisable" : ""} src="assets/icons/grid.svg" />
{ Object.keys(this.state.queryResult).length !== 0 ? <PatientInfoBlock data={this.state.queryResult} /> : null }
{ !this.state.queryResult ? <h3>Sorry no results match ''{this.state.inputValue}''</h3> : null }
</div>
);
}
'''
handleChange 应该是:
handleChange(selectedOption) {
this.setState({criteria: selectedOption});
}
selectedOption 类型是:
{
value: string,
label: string
}
想通了,感谢 armin yahya 将我指向正确的方向,因为我不知道 selectedOption 类型。 这是我最后写的,我的 handleChange function 工作正常,并为 API 调用更新 URL:
handleChange(selectedOption) {
if(selectedOption.value == 'Name') {
this.setState({criteria: 'Patient?name='});
}
if(selectedOption.value == 'bDay') {
this.setState({criteria: 'Patient?birthdate=eq'});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.