尝试利用查询参数
?来允许父级和子级访问当前选定的
topic。不幸的是,您将需要使用模块qs,因为
react-router-dom它不会自动解析查询(react-router v3可以)。
工作示例:https :
//presandbox.io/s/my1ljx40r9
URL的结构类似于连接字符串:
topic?topic=props-v-state
然后您将添加到查询中
&:
/topics/topic?topic=optimization&category=pure-components&subcategory=shouldComponentUpdate
✔使用匹配进行路由URL处理
✔不使用
this.props.location.pathname(使用
this.props.location.search)
✔用于
qs解析
location.search
✔不涉及骇客方法
Topics.js
import React from "react"; import { link, Route } from "react-router-dom"; import qs from "qs"; import Topic from "./Topic"; export default ({ match, location }) => { const { topic } = qs.parse(location.search, { ignoreQueryPrefix: true }); return ( <div> <h2>Topics</h2> <ul> <li> <link to={`${match.url}/topic?topic=rendering`}> Rendering with React </link> </li> <li> <link to={`${match.url}/topic?topic=components`}>Components</link> </li> <li> <link to={`${match.url}/topic?topic=props-v-state`}> Props v. State </link> </li> </ul> <h2> Topic ID param from Topic<strong>s</strong> Components </h2> <h3>{topic && topic}</h3> <Route path={`${match.url}/:topicId`} render={props => <Topic {...props} topic={topic} />} /> <Route exact path={match.url} render={() => <h3>Please select a topic.</h3>} /> </div> ); };另一种方法是创建一个
HOC将参数存储到的
state子项,
state当子项的参数更改时,子项会更新其父项。
URL的结构类似于文件夹树:
/topics/rendering/optimization/pure-components/shouldComponentUpdate
工作示例:https :
//presandbox.io/s/9joknpm9jy
✔使用匹配进行路由URL处理
✔不使用
this.props.location.pathname
✔使用lodash进行对象间比较
✔不涉及骇客方法
Topics.js
import map from "lodash/map"; import React, { Fragment, Component } from "react"; import NestedRoutes from "./NestedRoutes"; import links from "./links"; import createPath from "./createPath"; export default class Topics extends Component { state = { params: "", paths: [] }; componentDidMount = () => { const urlPaths = [ this.props.match.url, ":topicId", ":subcategory", ":item", ":lifecycles" ]; this.setState({ paths: createPath(urlPaths) }); }; handleUrlChange = params => this.setState({ params }); showParams = params => !params ? null : map(params, name => <Fragment key={name}>{name} </Fragment>); render = () => ( <div> <h2>Topics</h2> <links match={this.props.match} /> <h2> Topic ID param from Topic<strong>s</strong> Components </h2> <h3>{this.state.params && this.showParams(this.state.params)}</h3> <NestedRoutes handleUrlChange={this.handleUrlChange} match={this.props.match} paths={this.state.paths} showParams={this.showParams} /> </div> ); }NestedRoutes.js
import map from "lodash/map"; import React, { Fragment } from "react"; import { Route } from "react-router-dom"; import Topic from "./Topic"; export default ({ handleUrlChange, match, paths, showParams }) => ( <Fragment> {map(paths, path => ( <Route exact key={path} path={path} render={props => ( <Topic {...props} handleUrlChange={handleUrlChange} showParams={showParams} /> )} /> ))} <Route exact path={match.url} render={() => <h3>Please select a topic.</h3>} /> </Fragment> );


