React best practise / using parent component instance

let's imagine data that would look like that :

{
  {
    title: "great track",
    tags: ["techno"]
  },
  {
    title: "superb track",
    tags: ["house", "90s"]
  },
  ...
}

I render that in an html table, I have a component for the whole table, and a sub component for the tr (aka song title and tracks). so on each line I want to allow the users to be able to access a popup in which they can choose one or more tags for a song. I did it using reactstrap, it works ok.

I'm just a little disappointed by performance, it's quite ok, once it's built, but I saw how much longer it was to load when I added my modal on each line. So my first reflex, was to built only one modal in the parent component, and then use it from the sub component, and then I read articles on how, "one should not use the parent instance because it's bad"(tm).

I understand the point about dataflow, but in my example, having a modal waiting on each line while I'm sure I will never have two at the same time on screen feels like a waste of ressources.

Can anyone point me to an elegant way of building that kind of feature, in this particular context ?


Lifting state up to the parent component is a common practice in react, you can read articles in official documentation https://reactjs.org/docs/lifting-state-up.html

But there is one problem, when you use setState in your parent component, your songs table will render again and again, so you should care about it. One of the way is creating PureComponent for Songs table(if there is no changing in props, this component will not rerender)

I think, the code below is one of the way;

class Parent extends React.Component{
  state={
    tags: [],
    songs: {
        title: "great track",
        tags: ["techno"]
      },
      {
       title: "superb track",
       tags: ["house", "90s"]
      }
  }

  handlePopup(data){
    this.setState({tags: data});
  }

  render(){
    const {tags, songs} = this.state;
    cons isShowModal = tags && tags.length

    return (
      <div> 
          {isShowModal && <Modal data={tags} />}

          <SongsList data={songs} />
      </div>
    )
  }
}

class Parent extends React.PureComponent{
  render(){
    const {data} = this.props;

    return (
       <table><tbody>...render songs data</tbody></table>
     )
  }
}

Of course using modal in child rows is a waste of resources. you need to add a modal to parent and use props to show/hide it. also, you should use the key prop for your list items.

By default, when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there's a difference.

but when children have keys, React uses the key to match children in the original tree with children in the subsequent tree. it's good for performance.

链接地址: http://www.djcxy.com/p/52154.html

上一篇: 从组件内访问React树

下一篇: 回应最佳做法/使用父组件实例