preface

Today we’ll take a look at programmatic navigation and matching patterns in React


Programmatic navigation

1. Programmed navigation

Scenario: Click the login button and go to the home page after successful login. How do I do this? Programmatic navigation: through JS code to achieve page hopping

Push (path) : indicates the path to jump to a page. Go (n) : indicates the number of pages to move forward or back to a page. -1 means back to previous page)

class Login extends Component {
  handleLogin = () = > {
    // ...
    this.props.history.push('/home')}render(){... Omit other code}}Copy the code

2. Default route

Question: Now the route is displayed after clicking the navigation menu, how to display it when entering the page? Default Route: indicates the Route that will be matched when the page is displayed. The default Route path is: /

Second, matching mode

1. Fuzzy matching mode

Question: Why is the default route successfully matched when the Link component’s to attribute value is /login?

By default, React routes are fuzzy matching: The Route component matches as long as the path attribute of the Route component begins with the Link component’s to attribute

The code is as follows (example) :

<Link to="/login">The login page</Link>
<Route path="/" component={Home} />// Path represents the path attribute of the Route component. // PathName represents the TO attribute of the Link component.Copy the code

2. Exact match

Question: The default route is always displayed. How can I avoid this problem? Exact match: The Route is displayed only when the path and pathName match exactly

The code is as follows (example) :

// In this case, the component can only match pathName = / <Route exact path="/" component=... />
Copy the code

Recommended: Add the exact attribute to the default route.


conclusion

East or west, home is the best.