Reactjs 在react中从API调用呈现JSON数据
使用google maps API和Reactjs开发地理定位应用程序。我现在的目标是简单地将整个JSON数据呈现到窗口(稍后将使用)。没有错误,但没有任何内容呈现到页面。我是否正在尝试正确访问数据Reactjs 在react中从API调用呈现JSON数据,reactjs,api,geolocation,Reactjs,Api,Geolocation,使用google maps API和Reactjs开发地理定位应用程序。我现在的目标是简单地将整个JSON数据呈现到窗口(稍后将使用)。没有错误,但没有任何内容呈现到页面。我是否正在尝试正确访问数据 class App extends Component { constructor () { super(); this.state = { isLoaded: false, results: {} }; } componentDidMo
class App extends Component {
constructor () {
super();
this.state = {
isLoaded: false,
results: {}
};
}
componentDidMount() {
fetch(geo_url)
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
results: result.results
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const {error, isLoaded, results} = this.state;
if (error) {
return <div>Error: {error.message} </div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div className="App">
Location Data:
{results.geometry}
</div>
);
}
}
}
第一次渲染发生在检索结果之前。检查render()中是否已存在结果。如果没有,则显示“正在加载”消息
除此之外,修复您在尝试检索数据时对错误的处理。您正在设置未定义的state.error变量。然后,在渲染中,如果加载完成但出现错误,则显示错误消息 首先,您必须执行以下操作:
<div className="App">
{this.state.results.geometry}
</div>
{this.state.results.geometry}
或
render(){
const{results}=this.state
返回(
{results.geometry}
);
}
}
但就像@Yossi saids一样,结果并没有在第一次渲染中定义。这就是为什么你会说:“结果没有定义”。可以使用“lodash”强制渲染。即使我不知道这是否是一个好的做法,它仍然有效
您可以测试:
import _ from 'lodash';
render() {
const {results} = this.state
return (
{!_.isEmpty(results) &&
<div className="App">
{results.geometry}
</div>
}
);
}
从“lodash”导入;
render(){
const{results}=this.state
返回(
{!-.isEmpty(结果)&
{results.geometry}
}
);
}
应该是:)
PS:对不起,我的英语不好;) 您可以在状态中设置错误键:false 在componentDidMount中,更好地使用和捕获错误
componentDidMount() {
fetch(geo_url)
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
results: result.results
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
).catch(error) {
this.setState({
isLoaded: true,
error
})
}
}添加了错误消息处理程序,但现在它只是一个空白页。没有更多未定义的错误。首先,将if(!loaded)放在if(error)之前。这是逻辑顺序。另外,将state.error初始化为false。然后,检查错误,如下所述:
import _ from 'lodash';
render() {
const {results} = this.state
return (
{!_.isEmpty(results) &&
<div className="App">
{results.geometry}
</div>
}
);
}
componentDidMount() {
fetch(geo_url)
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
results: result.results
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
).catch(error) {
this.setState({
isLoaded: true,
error
})
}