如何访问地图内的下一个/上一个对象-反应? [英] How to access next/prev object inside map - react?
本文介绍了如何访问地图内的下一个/上一个对象-反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在特定对象内部生成next/prev链接时遇到问题. 这是我的代码.
I have problem with generate next/prev link inside specific object. It's my code.
someArrCars = [{name: 'somecar1', link: 'somelink1', vin: '123'}, {name: 'somecar2', link: 'somelink2', vin: '345'},...];
生成路线:
someArrCars.map( el => <Route path={el.link} component={() => <OnePageCar carVin={el.vin} key={el.vin}/>}
在一个对象内生成上一个/下一个链接
generate links prev/next inside one object
import React, { Component } from "react";
export default class OnePageCar extends Component {
render() {
const { carVin } = this.props;
someArrCars.map((el, index) => {
if (el.vin === carVin) {
return (
<React.Fragment key={el.vin}>
{someArrCars
.slice(index - 1, -(someArrCars.length - index))
.map(el => (
<Link src={el.link} />
))} {/* <== prev*/}
{someArrCars
.slice(index + 1, -(someArrCars.length - index - 2))
.map(el => (
<Link src={el.link} />
))} {/* <== next*/}
</React.Fragment>
);
}
});
}
}
我知道这是个疯狂的主意,但我不知道该怎么做...
I know it's a little crazy idea, but I don't know how to do it in another way...
推荐答案
从当前索引的前一个元素中减去1,然后将当前索引加1,以获取数组中的下一个元素.
subtract 1 from current index for the previous element and add 1 to current index to get the next element in an array.
import React, { Component } from "react";
export default class OnePageCar extends Component {
render() {
const { carVin } = this.props;
someArrCars.map((el, index) => {
const prevEl = someArrCars[index - 1];
const nextEl = someArrCars[index + 1];
if (el.vin === carVin) {
return (
<React.Fragment key={el.vin}>
<Link src={prevEl.link} /> {/* <== prev*/}
<Link src={nextEl.link} /> {/* <== next*/}
</React.Fragment>
);
}
});
}
}
这篇关于如何访问地图内的下一个/上一个对象-反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文