soa*_*rib 5 javascript arrays fetch reactjs
我的问题是关于如何在渲染返回()中显示数组结果。
我对 API 进行了提取,现在我得到了存储在数组中的结果。我需要显示此结果,但我尝试在 return 中使用 for{} 但它不起作用,我还尝试使用 .map 和map is undefined
.
fetch(url + '/couch-model/?limit=10&offset=0', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
}
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
}).then(json => {
this.setState({
models: json.results
}, () => {
/*console.log('modelosJSON: ', json);*/
});
})
render() {
const { isLoaded } = this.state;
const modelsArray = this.state.models;
console.log('modelos: ', modelsArray);
if (!isLoaded) {
return (
<div>Loading...</div>
)
} else {
return (
<div>
/*show results here*/
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
模型数组是results
从您的 返回的 json 的数组fetch
,因此您可以将其设置models
为您的状态,并设置isLoaded
为true
在加载模型时隐藏加载指示器。
例子
class App extends React.Component {
state = { isLoaded: false, models: [] };
componentDidMount() {
fetch(url + "/couch-model/?limit=10&offset=0", {
method: "GET",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: "JWT " + JSON.parse(localStorage.getItem("token")).token
}
})
.then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
})
.then(json => {
this.setState({
models: json.results,
isLoaded: true
});
});
}
render() {
const { isLoaded, models } = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
}
return <div>{models.map(model => <div key={model.id}>{model.code}</div>)}</div>;
}
}
Run Code Online (Sandbox Code Playgroud)