Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

react router - How to use onClick event on Link: ReactJS?

In React router, I have to and onClick attributes 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});
}
  • to attribute navigates to about Route
  • onClick assigns value to state variable selectedName which will be displayed when navigated to About page.

When I give timeout insided function called on click, its navigating to new page and after sometime state is getting updated resulting in displaying previous name until state is updated with new name.

Is there a way where it will navigate to the new route only after the code in onClick function gets executed.

You can get the entire code [here].(https://github.com/pushkalb123/basic-react-router/blob/master/src/App.js)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One possible way is, Instead of using Link, use history.push to change the route dynamically. To achieve that remove the Link component and define the onClick event on li. Now first perform all the task inside onClick function and at the end use history.push to change the route means to navigate on other page.

In your case change the router inside setState callback function to ensure that it will happen only after state change.

Write it like this:

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

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

Check this answers for:

When to use setState callback

How to navigate dynamically using react router dom


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...