我认为问题是该值仍然为空我需要设置值但我不知道如何设置。
constructor() {
super();
this.state = {
jsonReturnedValue: null
}
}
在这个区域中,我将值设置为 null 并尝试将其获取到我的反应中,但是当我运行它时,只能看到“员工列表”
fetch("http://localhost:5118/api/employeedetails/getemployeedetails")
.then(handleErrors)
.then(response => response.json()) .then(json => {
this.setState({ jsonReturnedValue: response.results });
}).catch(function(error) {
console.log(error);
});
}
}
render() {
return(
<div>
<h1> Listof Employees </h1>
<h1>{ this.state.jsonReturnedValue }</h1>
</div>
问题是
response.results
,因为 response
在第三次 then
调用中不可用,只有第二次调用才可用。
尝试:
fetch("http://localhost:5118/api/employeedetails/getemployeedetails")
.then(handleErrors)
.then(response => response.json())
.then(json => {
this.setState({ jsonReturnedValue: json.results });
}).catch(function(error) {
console.log(error);
});
使用 axios 进行 http 请求。并使用 console.log(response) 签入并承诺;响应是否来自 api
fetch
功能是否保留在您的 componentDidMount()
中?像这样:
componentDidMount() {
fetch('http://localhost:5118/api/employeedetails/getemployeedetails')
.then(resp => resp.json())
.then((resp) => {
console.log(resp);
this.setState({jsonReturnedValue: JSON.stringify(resp)});
}).catch(function(error) {
console.log(error);
});
}
另请注意,当您只想转储它并查看时,必须使用
this.setState({jsonReturnedValue: JSON.stringify(resp)})
=> resp
的字符串化版本。 (因为在render()
,你刚刚回来<h1>{ this.state.jsonReturnedValue }</h1>
)
但是,您可以循环(也许使用
.map
)jsonReturnedValue 并正确渲染每个员工,然后请删除 JSON.stringify