我的 fetch 给了我以下 JSON:
"{"name":"John","age":26,"city":"London"}"
但是,当我尝试像这样在我的页面上呈现它时:
import React from 'react';
import './App.css';
import * as microsoftTeams from "@microsoft/teams-js";
class Tab extends React.Component {
constructor(props){
super(props)
this.state = {
context: {}
}
}
componentDidMount() {
fetch("http://localhost/openims/json.php?function=getDocuments&input=")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
files: result.files
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, files } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{files.map(file => (
<li key={file.id}>
{file.name} {file.age} {file.city}
</li>
))}
</ul>
);
}
}
}
export default Tab;
我收到一个类型错误:无法读取未定义的属性“地图”
我怎样才能解决这个问题?
提前致谢!
鉴于 API 响应是{"name":"John","age":26,"city":"London"}
那么我建议如下:
将整个响应结果保存到 state 中。使用catch
块来捕获任何错误并设置任何错误状态,并使用finally
块来设置加载状态(更多DRY)。
componentDidMount() {
fetch("http://localhost/openims/json.php?function=getDocuments&input=")
.then(res => res.json())
.then((result) => {
this.setState({ ...result });
})
.catch((error) => {
this.setState({ error });
})
.finally(() => {
this.setState({ isLoaded: true })
});
}
从状态渲染,没有数组,只有状态字段。
render() {
const { error, isLoaded, name, age, city } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
<li>
{name} {age} {city}
</li>
</ul>
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句