Open iugo opened 6 years ago
我们还没有升级. 看到这样一句话: "经历了 React Router 升级重构的阵痛(你懂的)".
Route props getComponent 如何被替代的问题
https://reacttraining.com/react-router/web/guides/code-splitting
browserHistory.push() 如何被替代的问题
https://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router
在之前, 就在组内说过要使用 withRouter 来替代 browserHistory. 因为 v3 也是有 withRouter 的. 但目前看来, 效果还是不够理想.
路由注入的 props.params
如何被替代的问题
之前的项目中(可能是所有 react-router v3 共性), 所有 props 会被路由注入一些数据, v4 中则没有了. 我觉得这是比较好的, 任何注入最好显性. 现在可以通过 withRouter 包裹组件, 更明确地注入数据.
当使用 withRouter
包裹后, 之前的 props.params
等效于现在的 props.match.params
.
路由注入的 props.location.state
如何被替代的问题
下面列一下 withRouter 会注入的属性:
具体可以看 RouteComponentProps https://github.com/DefinitelyTyped/DefinitelyTyped/blob/0155a5a12ae7938fe092d6dde6c7a40b21613d5e/types/react-router/index.d.ts#L67
遇到 DOMException: Failed to execute 'pushState' on 'History'
错误
因为使用了 window.history
, 所以路由传递 state 不再是标准的 JS 传值, 而是要经过相关序列化. 在我们使用的过程中, 遇到过传递 moment 对象的情况, 因为 history 无法对 moment 对象进行序列化, 这时就会出错.
解决方法也简单, 主要讲值改为简单值就好, 比如不能包括未定义的 this. 对于 moment 的情况, 直接传 UNIX 时间戳, 或 ISO 标准值, 或 Date 对象均可.
基本完成了.
最近又在 twitter 中看到相关问题, https://twitter.com/ryanflorence/status/987101868948996099 .
所以在这里总结一下:
官方文档
v3 文档 https://github.com/ReactTraining/react-router/tree/v3/docs
v4 文档 https://reacttraining.com/react-router/
升级指南 https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/migrating.md
可能的不同
Route props path 类型
v3: https://github.com/ReactTraining/react-router/blob/v3/docs/guides/RouteMatching.md#path-syntax
v4: https://reacttraining.com/react-router/web/api/Route/path-string
location
v3 中 location.query 是有效的. https://github.com/ReactTraining/react-router/blob/v3/docs/Glossary.md#location
v4 中似乎移除了: https://reacttraining.com/react-router/web/api/location