如何在React中从2个Urls输出匹配数据?

时间:2018-12-22 15:04:12

标签: reactjs api react-native fetch coinbase-api

我正在从2个链接,硬币列表和事件列表中获取数据。数据将在渲染部分渲染。

  componentDidMount() {
Promise.all([
  fetch('https://coindar.org/api/v2/coins?access_token=36174:fy7i3eWjxllsdwhl80c'),
  fetch('https://coindar.org/api/v2/events?access_token=36174:fy7i3eWjxllsdwhl80c&page=1&page_size=30&filter_date_start=2018-10-01&filter_date_end=2020-07-01&sort_by=views&order_by=1')])
    .then(([res1, res2]) => Promise.all([res1.json(), res2.json()]))
    .then(([data1, data2]) => this.setState({
      events: data2, 
      coins: data1,
      coinid: [],
      isLoaded: true,
    }));
}

 render() {
var {isLoaded, events, coins,coinid} = this.state;
  return (
    <div className="App">
    <ul>
    {events.map(events => (
      <li key={events.id} value={events.coin_id} > Name: {events.caption} Coin id: {events.coin_id} <!-- Image here.. coins.image_32 --> </li>))}
    </ul>
    <ul>
    {coins.map(coins => (
      <li key={coins.id}> Name: {coins.name} : Coin id: {coins.id}</li>))}
    </ul>
    </div>
  );
 }
}

可以复制粘贴URL以查看数据,我要实现的是事件列表(第二个URL)及其图像和硬币名称(第一个URL)。在其他语言中,第一步可能是使用where子句(where events.coin_id == coin.id),但是,我不确定如何使用React进行处理。

1 个答案:

答案 0 :(得分:0)

看起来没有任何反应,它的纯javascript实现足以实现我们所需的功能。

只需引入另外2个状态属性,例如matchEventsmatchCoins,并应用 where子句(其中events.coin_id == coin.id)

我不确定这里是否需要2个过滤器,只需根据需要进行修改即可。

componentDidMount() {
    Promise.all([
        fetch('https://coindar.org/api/v2/coins?access_token=36174:fy7i3eWjxllsdwhl80c'),
        fetch('https://coindar.org/api/v2/events?access_token=36174:fy7i3eWjxllsdwhl80c&page=1&page_size=30&filter_date_start=2018-10-01&filter_date_end=2020-07-01&sort_by=views&order_by=1')])
        .then(([res1, res2]) => Promise.all([res1.json(), res2.json()]))
        .then(([data1, data2]) => this.setState({
            events: data2,
            coins: data1,
            matchEvents: data2.filter(event => {
                return data1.some(coin => events.coin_id == coin.id)
            }),
            matchCoins: data1.filter(coin => {
                return data2.some(event => events.coin_id == coin.id)
            }),
            coinid: [],
            isLoaded: true,
        }));
}

render() {
    var { isLoaded, events, coins, coinid, matchEvents, matchCoins } = this.state;
    return (
        <div className="App">
            <ul>
                {matchEvents.map(events => (
                    <li key={events.id} value={events.coin_id} > Name: {events.caption} Coin id: {events.coin_id} <!-- Image here.. coins.image_32 --> </li>))}
            </ul>
            <ul>
                {matchCoins.map(coins => (
                    <li key={coins.id}> Name: {coins.name} : Coin id: {coins.id}</li>))}
            </ul>
        </div>
    );
}