[英]How to resolve " Cannot read property 'map' of undefined" error in React Js
[英]How to solve Cannot read property 'map' of undefined error in React js?
我正在使用json-server
構建一個帶有虛擬后端的 react js 應用程序。我正在實現一個下拉列表,但在從 api 獲取時Cannot read property 'map' of undefined error
。api 在瀏覽器中工作正常,但在獲取時反應它給了我這個錯誤。
我的組件:
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>
有人可以幫我解決這個錯誤嗎?
您沒有正確使用 fetch :
fetch('http://localhost:5000/groups').then((res) => {
res.json().then((json) => {
values = json;
this.setState({options: values.groups})
console.log(values);
})
})
兩件事應該是正確的。
{ this.state.options.map((option, key) => <option key={key} >{option}</option>) }
在此您嘗試將 object 綁定為反應子級,所以不是這個它應該是{{ this.state.options.map((option, key) => <option key={key} >{option["apis"]}</option>) }
this.setState({options: json.groups})
這是您的代碼的工作示例(獲取調用不同): https://codesandbox.io/embed/nifty-lamport-mzmro?fontsize=14&hidenavigation=1&theme=dark
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.