gpt4 book ai didi

javascript - 在 react-router v4 中获取路径参数

转载 作者:可可西里 更新时间:2023-11-01 02:34:35 28 4
gpt4 key购买 nike

我正在尝试通过我的应用程序构建路由器链接,

在这个场景中,我有三个文件。

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 编号)

我很难理解的是如何 setState({iPressedThisBook})当按下 <Link>或者如果我可以使用 /12345 之后的部分像过滤器一样创建

因为在 App Route将被连接为...

<Route path="/details/:id" render={() => (
<BookDetailedView
bookStateUpdated = {this.bookStateUpdated}
book = {this.state.books}
/>
)}/>

稍后,我想捕获 :id这样我就可以制作一个 this.props.book.find(:id)在我的里面<BookDetailedView>

最佳答案

为了在您的组件中接收路径参数,您需要首先将您的组件与withRouter 连接起来。 HOC 来自 react-router这样您就可以访问 Router Prop 并获取路径 params来自 match Prop 为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) ;

或者简单地在路由中使用 render prop 传递它作为

<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:

  1. Route component as this.props.match
  2. Route render as ({ match }) => ()
  3. Route children as ({ match }) => ()
  4. withRouter as this.props.match
  5. 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 中获取路径参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45468837/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com