簡體   English   中英

如何使用searchbox中的搜索詞從ReactJS中的多個URL獲取JSON數據?

[英]How to get JSON data from multiple URLS in ReactJS using search term in searchbox?

我想從多個網址獲取json數據並將其顯示在前端。 以下是網址:

1) localhost:3000/api/getdata1

2) localhost:3000/api/getdata2

3) localhost:3000/api/getdata3

而不是在每個網址上都使用.fetch(),如下所示:

.fetch('localhost:3000/api/getdata1')

.fetch('localhost:3000/api/getdata2')

.fetch('localhost:3000/api/getdata3')

我將利用Promise,但如何將搜索框的搜索詞作為查詢傳遞給api端點? 有沒有更有效的方法或更好的方法來做到這一點(在ReactJS中)->從搜索框中獲取搜索詞,然后使用ES6的模板字符串功能將該搜索詞注入api端點內。

const dataurls = [
    'localhost:3000/api/getdata1/q={searchterm}',
    'localhost:3000/api/getdata2/q={searchterm}',
    'localhost:3000/api/getdata3/q={searchterm}'
];
const promisedurl = dataurls.map(httpGet);

Promise.all(promisedurls)
.then(data=> {
    for (const d of data) {
        console.log(d);
    }
})
.catch(reason => {
    // Receives first rejection among the Promises
});

您可以使用template literal將搜索searchterm添加到您的網址中。

 const searchterm = 'abc'; const dataurls = [ `localhost:3000/api/getdata1/q=${searchterm}`, `localhost:3000/api/getdata2/q=${searchterm}`, `localhost:3000/api/getdata3/q=${searchterm}` ]; console.log(dataurls); 

如果我正確理解問題,一種解決方法可能是

const dataUrls = [
    'localhost:3000/api/getdata1',
    'localhost:3000/api/getdata2',
    'localhost:3000/api/getdata3'
];

const dataRequests = dataUrls.map((apiEndpoint) => fetch(`${apiEndpoint}/q=${searchTerm}`));

Promise.all(dataRequests)
.then((data) => {
    for (const d of data) {
        console.log(d);
    }
})
.catch(reason => {
    // Receives first rejection among the Promises
});

盡管這並不是每個人react說出來的,但這應該可以完成工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM