dhu*_*lme 3 reactjs react-router
在 React Router 4 中,我可以定义
<Route path="/calendar/:view/:year?/:month?/:day?" component={Calendar} />
Run Code Online (Sandbox Code Playgroud)
将道具从 URL 传递到我的日历组件。
在 Calendar 组件中,我想以编程方式设置 URL 参数。文档显示了如何使用 来执行此操作history.push(),但这需要您像history.push(``${view}/${year}/${month}/${day}``). 但我想在不耦合到路由结构的情况下更新 URL,理想情况下类似于history.push({ view: 'month', year: '2018' }).
这可能吗?我觉得 React Router 帮助将 URL 拆分为参数似乎很奇怪,但没有提供设置这些参数的好机制?
我通过使用 match.path 和 generatePath 来做到这一点。下面是一个例子:
this.props.history.push({
pathname: generatePath(this.props.match.path, {orderId: "latest", orderItemId: "latest"})
});
Run Code Online (Sandbox Code Playgroud)
你可以在这里阅读它https://reacttraining.com/react-router/core/api/generatePath和这里https://reacttraining.com/react-router/core/api/match。
这是迄今为止我发现的最干净的解决方案,用于防止路由组件知道它稍后将在路径结构中分配的位置。也许它适合您(或其他人)的需要。
我设法使用path-to-regexpReact Router 使用的包来实现这一点:
this.props.history.push(pathToRegexp.compile(this.props.match.path)({ view: 'month', year: '2018' ));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8077 次 |
| 最近记录: |