繁体   English   中英

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

[英]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 (....

现在被卡住了一段时间。 任何帮助表示赞赏

您应该对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以获得更多唯一块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM