乐闻世界logo
搜索文章和话题

What is withRouter for in react-router-dom ?

1个答案

1

withRouter is a Higher-Order Component (HOC) in the react-router-dom library. Its purpose is to provide route-related props (such as history, location, and match) to components, even when these components are not route components (i.e., not directly rendered by <Route>). Using withRouter enables deeply nested components to access route information, which is very useful in many scenarios, especially when a component needs to know the current route state but is not directly wrapped by <Route> in the route tree.

Usage Example:

Suppose we have a UserProfile component that displays user details but is located deep within the application hierarchy, not directly rendered by <Route>. To access the current route information (e.g., the user ID in the URL) within UserProfile, we can wrap it with withRouter:

javascript
import React from 'react'; import { withRouter } from 'react-router-dom'; class UserProfile extends React.Component { componentDidMount() { // Access route parameters let userId = this.props.match.params.userId; this.fetchUserData(userId); } fetchUserData(userId) { fetch(`/api/users/${userId}`) .then(response => response.json()) .then(data => { // Process user data console.log(data); }); } render() { return ( <div> <h1>User Profile</h1> {/* Display user information */} </div> ); } } // Wrap the UserProfile component with the withRouter Higher-Order Component export default withRouter(UserProfile);

In this example, the UserProfile component itself does not directly receive route props, but by using withRouter, it can access this.props.match.params.userId to retrieve the user ID from the URL and then fetch and display the user data based on that ID.

Therefore, UserProfile can be placed flexibly anywhere in the application without worrying about how to receive route information.

2024年6月29日 12:07 回复

你的答案