javascript – 在react-router v4中获取路径参数
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 在react-router v4中获取路径参数,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2130字,纯文字阅读大概需要4分钟。
内容图文
我正在尝试通过我的应用程序构建路由器链接,
在这种情况下,我有三个文件.
App.js
Book.js
DetailedView.js
我在Book里面建立了一个< Link>仅在悬停时出现(在书籍封面上)
{this.state.isHovered ? (
<Link to={`/details/${this.props.book.industryIdentifiers[1].identifier}`}>
<div className="hover-box"></div>
</Link>) : ( <div /> )}
这将带我到/ details / 12345(isbn10号码)
我很难理解的是例如如何
按下< Link>时的setState({iPressedThisBook})或者如果我可以使用/ 12345之后的部分来创建过滤器
因为在App中,路线将被连接为…
<Route path="/details/:id" render={() => (
<BookDetailedView
bookStateUpdated = {this.bookStateUpdated}
book = {this.state.books}
/>
)}/>
我,稍后,想要获取:id,以便我在我的< BookDetailedView>内部制作一个this.props.book.find(:id).
解决方法:
为了在您的组件中接收路径参数,您需要首先将您的组件与来自react-router的withRouter HOC连接,以便您可以访问路径道具并从匹配道具中获取路径参数this.props.match.params .ID
示例代码:
import {withRouter} from 'react-router';
class BookDetailedView extends React.Component {
render() {
var id = this.props.match.params.id
}
}
export default withRouter(BookDetailedView) ;
或者简单地将其与路线中的渲染道具一起传递
<Route path="/details/:id" render={({match}) => (
<BookDetailedView
bookStateUpdated = {this.bookStateUpdated}
book = {this.state.books}
id={match.params.id}
/>
)}/>
来自match的React文档
match
A match object contains information about how a
<Route path>
matched
the URL.match
objects contain the following properties:
- params – (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path
- isExact – (boolean) true if the entire URL was matched (no trailing characters)
- path – (string) The path pattern used to match. Useful for building nested s
- url – (string) The matched portion of the URL. Useful for building nested s
You’ll have access match objects in various places:
- Route component as
this.props.match
- Route render as ({ match }) => ()
- Route children as ({ match }) => ()
- withRouter as this.props.match
- matchPath as the return value
If a Route does not have a path, and therefore always matches, you’ll
get the closest parent match. Same goes for withRouter
内容总结
以上是互联网集市为您收集整理的javascript – 在react-router v4中获取路径参数全部内容,希望文章能够帮你解决javascript – 在react-router v4中获取路径参数所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。