Reactjs 如何在“redux-router5”中以编程方式导航到不同的路由?
我正在应用程序中使用Reactjs 如何在“redux-router5”中以编程方式导航到不同的路由?,reactjs,react-router,react-redux,Reactjs,React Router,React Redux,我正在应用程序中使用redux-router5来管理路线。我将路线定义为以下代码: const Root = () => ( <Provider store={store}> <RouterProvider router={router}> <MyComponent /> </RouterProvider> </Provider>
redux-router5
来管理路线。我将路线定义为以下代码:
const Root = () => (
<Provider store={store}>
<RouterProvider router={router}>
<MyComponent />
</RouterProvider>
</Provider>
);
router.start((err, state) => {
ReactDOM.render(<Root/>, document.getElementById('root'));
});
在MyComponent
中,我可以通过其属性访问路由器实例,但它没有可供我使用的navigate
方法。它只有路由参数、名称、路径等。因此,如何在组件中导航到不同的路由?我已经看过了
它似乎是这样工作的:
import { connect } from 'react-redux';
import { actions } from 'redux-router5'
class SimpleComponent extends React.Component {
redirectToDashboard = () => this.props.navigateTo('/dashboard');
render() {
return (
<button onClick={this.redirectToDashboard}>go to dashboard</button>
)
}
}
export default connect(null, { navigateTo: actions.navigateTo })(SimpleComponent);
值得一提的是,若组件在那个时呈现,那个么它已经“连接”了,不需要使用路由器
import { connect } from 'react-redux';
import { actions } from 'redux-router5'
class SimpleComponent extends React.Component {
redirectToDashboard = () => this.props.navigateTo('/dashboard');
render() {
return (
<button onClick={this.redirectToDashboard}>go to dashboard</button>
)
}
}
export default connect(null, { navigateTo: actions.navigateTo })(SimpleComponent);
import { withRouter } from 'react-router'
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
redirectToDashboard = () => this.props.history.push('/dashboard');
render() {
const { match, location, history } = this.props
return (
<div onClick={this.redirectToDashboard}>You are now at {location.pathname}</div>
)
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)