【发布时间】:2021-08-23 14:32:46
【问题描述】:
我正在使用 json-server 构建一个带有虚拟后端的 react js 应用程序。我正在实现一个下拉列表,但我在从 api 获取时得到 Cannot read property 'map' of undefined error。该 api 在浏览器中运行良好,但在获取 react 时它是给我这个错误。
我的组件:
import React from 'react';
var values;
class ApiDropDown extends React.Component {
constructor(){
super();
this.state = {
options: []
}
}
componentDidMount(){
this.fetchOptions()
}
fetchOptions(){
fetch('http://localhost:5000/groups')
.then((res) => {
return res.json();
}).then((json) => {
values = json;
this.setState({options: values.groups})
console.log(values);
});
}
render(){
return <div>
<select>
{ this.state.options.map((option, key) => <option key={key} >{option}</option>) }
</select>
</div>;
}
}
export default ApiDropDown;
我的 db.json 用于虚拟后端:
{
"groups":[
{
"key":"version",
"apis":"system_info"
},
{
"key":"admin",
"name":"patients"
},
{
"id":"admin2",
"name":"doctors"
}
]
}
这是我渲染 ApiDropDown 组件的方式:
return (
<form className="add-form" onSubmit={onSubmit}>
<div>
<ApiDropDown/> //ApiDropDown Component
</div>
<div >
<input className="clientparams"
type="text"
placeholder="Add Client"
value={client_name}
onChange={(e) => setText(e.target.value)}
/>
</div>
</form>
有人可以帮我解决这个错误吗?
【问题讨论】:
-
在你的控制台日志中你能完美地看到你的数据吗?
-
是的,我正在 console.log 中获取数据
标签: javascript html json reactjs api