新手问题。
我有一个需要添加到的数组,我正在使用切片来执行此操作。我正在使用 Gatsby / react 。我遇到的问题是每次我的页面/组件重新渲染我添加到数组中的对象时都会再次添加
这是我的代码
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
,例如以获得更独特的 block 。
关于javascript - 在 react 中使用 splice 添加到数组的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53366957/