gpt4 book ai didi

javascript - componentWillMount 中的多个 fetch 语句

转载 作者:行者123 更新时间:2023-11-28 04:39:47 25 4
gpt4 key购买 nike

首先,我使用 componentWillMount() 来填充 articles 属性(这有效,没问题)。我迭代这些值以在某些容器/组件上显示不同的图像/文本。

我现在遇到的问题是,我现在还想使用 componentWillMount 用单个图像填充 background 属性。我认为我可以使用 '' 而不是 [],但我不确定如何进行这两个 API 调用。

我已经做了足够的研究,知道我的答案可能在于 promise ,但我无法从示例中推断出它们将如何应用于我的特定问题。有任何想法吗?

constructor(props) {
super(props);
this.state = {
articles: [],
backgroundz: '',
};
}


componentWillMount() {
fetch('http://localhost:8000/api/getArticles')
.then(function (response) {
return response.json();
})
.then(function (json) {
this.setState({
articles: json,
});
}.bind(this));

fetch('http://localhost:8000/api/getBackground')
.then(function (response) {
return response.json();
})
.then(function (json) {
this.setState({
backgroundz: json,
});
}.bind(this));
}

最佳答案

您将需要在 componentDidMount 中执行初始 AJAX 请求,如 the React documentation 所示。

除此之外,这些获取请求的语法有点不对劲。如果 props 不会在构造函数中使用,也没有理由将它们传递到构造函数或 super 中,通常应该避免这样做。我将其重构为如下所示:

constructor() {
super();
this.state = {
articles: [],
backgroundz: '',
};
}


componentDidMount() {
fetch('http://localhost:8000/api/getArticles')
.then(response => response.json())
.then(articles => this.setState({ articles });

fetch('http://localhost:8000/api/getBackground')
.then(response => response.json())
.then(backgroundz => this.setState({ backgroundz });

}
}

关于javascript - componentWillMount 中的多个 fetch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43882017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com