![](/img/trans.png)
[英]what is the correct way to splice an array using for loop, having nested if conditions
[英]What is the correct way to add to an array with splice in react
新手问题。
我有一个我需要添加的数组,并且我正在使用slice来做到这一点。 我正在使用盖茨比/反应。 我的问题是每次我的页面/组件重新呈现要添加到数组中的对象时,都会再次添加它
这是我的代码
class IndexPage extends PureComponent {
render() {
const data = this.props.data;
const hostels = data.featuredHostel.edges;
const hopimage = data.hop.childImageSharp.fluid;
hostels.splice(8, 0, {
node: {
featuredImage: {
alt: 'Bedhopper Image',
fluid: hopimage
},
id: 'bedhopper',
slug: '/deals/bed-hopper',
title: 'For travel adicts who want to stay everywhere'
}
});
return (....
现在被卡住了一段时间。 任何帮助表示赞赏
您应该对constructor
或componentDidMount
进行任何计算。
class IndexPage extends PureComponent {
constructor(props) {
super(props);
this.state = {
hostels: props.data.featuredHostel.edges.concat(...)
}
}
componentDidMount() {
}
render() {
const { hostels } = this.state;
return (
...
)
可能您的案例也可以工作(我没有看到完整的代码)。 我猜你使用数组索引作为渲染的关键
hostels.map((hostel, hostelIndex) => (<SomeComponent key={hostelIndex} />))
例如,您可以将key更改为hostel.id
以获得更多唯一块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.