我的任务是为POC创建前端。我不是前端开发人员,但我选择使用React JS。从多个API端点获取数据的页面只有一页。API端点返回一个简单的json对象。我设法使它正常工作,但是我的代码很丑陋,我想创建一个函数来处理所有这些问题,但是我似乎无法正确地做到这一点。这是我的代码
export default class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
group1: [],
group2: [],
group3: [],
isLoaded: false,
}
}
componentDidMount() {
const group1_url = "http://localhost/api/1"
const group2_url = "http://localhost/api/2"
const group3_url = "http://localhost/api/3"
fetch(group1_url)
.then(res => res.json())
.then(json => {
this.setState({
group1: json,
})
});
fetch(group2_url)
.then(res => res.json())
.then(json => {
this.setState({
group2: json,
})
});
fetch(group3_url)
.then(res => res.json())
.then(json => {
this.setState({
group3: json,
})
});
}
我正在尝试创建一个像这样的函数:
function fetch_data(url, state) {
fetch(url)
.then(res => res.json())
.then(json => {
this.setState({
state: json,
})
});
}
var group1 = fetch_data(group1_url, group1);
到目前为止没有喜悦。如何创建函数来获取数据并在js中设置状态?另外,如何使我的代码看起来更好呢?还是还有其他我应该使用/研究的东西?
传递字符串作为第二个参数,并使用计算属性:
function fetch_data(url, state) {
fetch(url)
.then(res => res.json())
.then(json => {
this.setState({
[state]: json,
})
});
}
fetch_data(group1_url, 'group1');
我也强烈建议捕获错误-尽可能避免出现未处理的拒绝。
您可能需要使用Promise.all
等待所有组加载:
const dataSources = {
group1: 'http://localhost/api/1',
group2: 'http://localhost/api/2',
group3: 'http://localhost/api/3',
};
Promise.all(
Object.entries(dataSources).map(([propertyName, url]) => (
fetch(url)
.then(res => res.json())
.then((result) => {
this.setState({
[propertyName]: result
})
})
))
)
.then(() => {
this.setState({ isLoaded: true })
})
.catch((error) => {
// handle errors
})
(还要注意,您的json
参数不是JSON -JSON只是存在于字符串中的一种格式。已反序列化的内容只是一个普通的对象或数组。最好像result
我一样称呼它来减少误导)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句