用React进行拼接添加到数组的正确方法是什么

时间:2018-11-19 00:43:28

标签: javascript arrays reactjs gatsby array-splice

新手问题。

我有一个数组需要添加,我正在使用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 (....

现在,芬恩坚持了一段时间。任何帮助表示赞赏

1 个答案:

答案 0 :(得分:3)

您应该对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} />))

例如,您可以将密钥更改为hostel.id,以获取更多唯一块。

相关问题