简体   繁体   中英

Force rerender of some components when a button is click - React

From my server file I have function that will pull up a set of data's based on the id.

app.get('/musicbyid', function(req, res){
    var query = req.query.term.toLowerCase();
    music.find({ _id: query }, function(err, allMusic){
      if(err){
      console.log(err);
      } else {
      res.json(allMusic);
      }
  }) 
    console.log(req.query.term);
  });

and then on my react file I have a getMusicById function which will get the the click id and render the MusicListDetail Component w/c has specific info about the item that was clicked:

class App extends Component{
 constructor(props){
   super(props);

   this.state = { 
     music: [],
     selectedMusic: null
  };

getMusicById(id) {
  axios.get('/musicbyid', {
      params: {
          id: id
      }
  })
  .then(music => this.setState({
      selectedMusic: music.data._id
  }))
  .then(() => console.log('this is is a state >>>>+++', this.state))
  .catch((err) => console.log(err));
}

This is a component where I listed all of the music that can be clicked vis button:

class MusicListItem extends Component{

  onClickImgMoreBtn(){
    console.log('hi there!');
   }

  render(){
  return (
 <a onClick={this.onClickImgMoreBtn} href={this.props.music._id} >
 <img className="card-img-top" src={this.props.music.poster_path} /></a>
  );

Again, when the button triggered via onClickImgMoreBtn was clicked it must then re-render the dom with the detail for that specific id with the ff component:

 const MusicDetail = ({music}) => {
  return (

      MUSIC ID:</strong>{music._id}</h4>
      MUSIC TITLE:</strong> {music.title}</h4>
  );

But I don't want to render all of the available components so I was thinking on how I can do a conditional statement to only render the header and the footer when the MusicDetail component was being re-rendered upon button clicked on the list.

  1. How can I rerender the dom with the detail of the click id music detail
  2. How can I do a conditional statement to render only a specific component while on the music detail component. Let's say I only want to render <Header /> and <Footer />

    Sorry I am a beginner and I am really thinking hard on how I can pull all of these stuffs together.

From React documentation

React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.

So if you have separated components like <Header/> and click on button will pass some new props to this component, that will not case entire DOM re-rendering. Only this exact component will be changed

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