如何使用搜索框中的搜索词从ReactJS中的多个URL获取JSON数据?

时间:2018-03-17 06:50:52

标签: javascript reactjs ecmascript-6

我想从多个url获取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
});

2 个答案:

答案 0 :(得分:1)

您可以使用template literalsearchterm添加到您的网址。

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);

答案 1 :(得分:1)

如果我理解正确的问题,一种方法可能是

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特定的,但这应该可以完成工作。