简体   繁体   中英

setState when choose a react-router (React)

I create a web application in the react framework. I am trying to change the state to text when I enter the appropriate router. How can I write it to make it work correctly?

class Header extends React.Component {
  state = {
    title: ""
  };

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

    return (
      <div>
        <Typography variant="h6" color="inherit" noWrap>
          {title}
        </Typography>
        <Switch>
          <Route exact path="/" component={HomePage} title="Dashboard" />
          <Route path="/payment" component={FeaturePage} title="Payment" />
          <Route path="" component={NotFoundPage} />
        </Switch>
      </div>
    );
  }
}

You can pass in an update function to your components while still using React router like so.

class Header extends React.Component {
state = {
    title: ""
};

updateTitle(newTitle){
    this.setState({title: newTitle})
}

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

return (
  <div>
    <Typography variant="h6" color="inherit" noWrap>
      {title}
    </Typography>
    <Switch>
      <Route exact path="/" render={()=> <HomePage updateTitle={this.updateTitle}/>} title="Dashboard" />
      <Route path="/payment" render={()=> <FeaturePage updateTitle={this.updateTitle}/>} title="Payment" />
      <Route path="" component={NotFoundPage} />
    </Switch>
  </div>
);
}
}

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