我正在从两个链接、一个硬币列表和一个事件列表获取数据。数据在渲染部分渲染。
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>
);
}
}
可以复制粘贴网址来查看数据,我想要实现的是事件列表(第二个网址)及其图像和硬币名称(第一个网址)。在其他语言中,第一步可能是使用
where
子句 (where events.coin_id == coins.id
),但是,我不确定如何使用 React 来实现它。
看起来和react没什么关系,纯粹的javascript实现就足以实现我们想要的功能了。
只需引入另外 2 个状态属性,例如
matchEvents
和 matchCoins
,应用 where 子句 (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>
);
}