javascript - 在 react 中使用 splice 添加到数组的正确方法是什么

标签 javascript arrays reactjs gatsby array-splice

新手问题。

我有一个需要添加到的数组,我正在使用切片来执行此操作。我正在使用 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 (....

现在已经被困在这个问题上有一段时间了。任何帮助表示赞赏

最佳答案

您应该对 constructorcomponentDidMount 进行任何计算。

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/

相关文章:

javascript - 如何在函数中替换 this.props.dispatch ?

javascript - 管理对同一个 Apollo 突变的多次调用

javascript - 当用户更改输入时,React 不会更新组件状态

javascript - 滑入/滑出导航

java - 如何根据 String 类型方法(java)中的 if 语句返回多个值?

c++ - const 字符串仍然更可取吗?

javascript - 将数据从 React 传递到 Node Express 服务器

javascript - Facebook Javascript SDK 中的好友列表总数

javascript - jQuery .index(),将更改与参数混淆

arrays - 更新/更改自定义对象的数组值 - swift