How to use onClick event in Link: ReactJS?

In React router, I have attributes before and onClick , as shown below

<li key={i}><Link to="/about" onClick={() => props.selectName(name)}>{name}</Link></li>

state = {
    selectedName: ''
};

selectName = (name) => {
   setTimeout(function(){this.setState({selectedName:name});}.bind(this),1000);
   // this.setState({selectedName: name});
}
  • Attribute
  • - moves to the "Route" position
  • onClick assigns a value to the state selectedName variable, which will be displayed when navigating the About page.

When I provide a function with the timeout enabled by a click, its transition to a new page and after some state is updated, which leads to the display of the previous name until the state is updated with the new name.

Is there a way that it will move along the new route only after the code has been launched in the onClick function.

[]. (https://github.com/pushkalb123/basic-react-router/blob/master/src/App.js)

+4
2

: Link history.push . Link onClick li. onClick history.push, , .

setState callback, , .

:

<li key={i} onClick={() => props.selectName(name)}> {name} </li>

selectName = (name) => {
    this.setState({ selectedName:name }, () => {
        this.props.history.push('about');
    });
}

:

setState

+2

, URL Params, , . , , / , /about/tom /about/pushkal. , , - URL- index.js:

<Route path="/about/:name" component={AboutPage}>

, about, :

<Link to={"/about/" + name}>{name}</Link>

, AboutPage, param this.props.params.name. .

, ,

+1

Source: https://habr.com/ru/post/1692292/


All Articles