简体   繁体   中英

What is the correct way to add to an array with splice in react

Newbie question.

I have an array that i need to add to and I am using slice to do this. I am using gatsby/react. The problem I have is each time my page/component rerenders the object I am adding to my array gets added again

Here is my code

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 (....

Been stuck on this for a while now. Any help appreciated

You should make any calculation on constructor or componentDidMount .

class IndexPage extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      hostels: props.data.featuredHostel.edges.concat(...)
    }
  }

  componentDidMount() {

  }

  render() {
    const { hostels } = this.state;

    return (
      ...
    )

Probably, your case can works too (I didn't see whole code). I guess you use array index as key for render

hostels.map((hostel, hostelIndex) => (<SomeComponent key={hostelIndex} />))

You can change key to hostel.id for example for more unique block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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