【发布时间】:2019-02-26 18:25:44
【问题描述】:
我已经创建了一个应用程序,并且想添加更多组件,这些组件将使用我在“personlist.js”中获取的相同 json,所以我不想在每个应用程序中都使用 fetch(),我想做一个只做fetch的单独组件,在其他组件中调用它,然后在每个组件中映射函数,如何使只获取组件?
这是我的获取方法:
componentDidMount() {
fetch("data.json")
.then(res => res.json())
.then(
result => {
this.setState({
isLoaded: true,
items: result.results
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
这是一个沙盒 sn-p https://codesandbox.io/s/1437lxk433?fontsize=14&moduleview=1
【问题讨论】:
-
您可以(并且应该:-))在此处现场制作可运行的示例,这样您就不会意外遗漏重要代码。 Stack Snippets 支持 React,包括 JSX; here's how to do one。 (他们也应该是minimal。)
标签: javascript json reactjs web-applications jsx