我在我的应用中使用redux-router5
来管理路线。我将路线定义为以下代码:
const Root = () => (
<Provider store={store}>
<RouterProvider router={router}>
<MyComponent />
</RouterProvider>
</Provider>
);
router.start((err, state) => {
ReactDOM.render(<Root/>, document.getElementById('root'));
});
下面是商店中间件的代码:
export default function configureStore(router) {
// create the middleware for the store
const createStoreWithMiddleware = applyMiddleware(
router5Middleware(router),
ReduxPromise,
ReduxThunk,
)(createStore);
const store = createStoreWithMiddleware(reducers);
router.usePlugin(reduxPlugin(store.dispatch));
return store;
}
在MyComponent
中,我可以通过其属性访问路由器实例,但它没有navigate
方法供我使用。它只有路由参数,名称,路径等。那么我如何导航到组件内的不同路径?
答案 0 :(得分:1)
似乎它的工作方式如下:
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);
原始回答:
我不知道如何使用redux-router5
导航(乍一看主要用于与redux一起使用的文档),但回答你的问题:
那么如何导航到组件内的不同路径?
使用来自'react-router'的withRouter
HOC:
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)
值得一提的是,如果组件由Route component呈现,则它已经“已连接”且不需要withRouter
。