正如我在你的问题中看到的,你正在使用Link
导航。考虑到您还想通过 Link 发送数据,您可以向其传递一个对象而不是string path
如中提到的React-router 文档 https://reacttraining.com/react-router/web/api/Link,所以你可以通过state object
in TableRow
类似组件
const {name, time, episodeId, img} = this.props;
<Link to={{pathname:showUrl, state: {show: {name, time, episodeId, img }}}}>{this.props.name}</Link>
现在您可以在以下位置检索此信息Show
组件为
this.props.location.state && this.props.location.state.name
您需要注意的另一件事是,您需要将道具传递给渲染函数
<Switch>
<Route
exact
path="/"
render={(props) => {
return <Table shows={this.state.shows} {...props}/>;
}}
/>
<Route
path="/show/:showID"
render={(props) => {
return <Show {...props}/>;
}}
/>
<Route component={FourOhFour} />
</Switch>
现在,上述解决方案仅在您从应用程序内部导航时才有效,但如果您更改 URL,它将不起作用,如果您想使其更加健壮,则需要将数据传递给显示组件,然后进行优化在生命周期函数中
你会 。这样做就像
<Switch>
<Route
exact
path="/"
render={(props) => {
return <Table shows={this.state.shows} {...props}/>;
}}
/>
<Route
path="/show/:showID"
render={(props) => {
return <Show shows={this.state.shows} {...props}/>;
}}
/>
<Route component={FourOhFour} />
</Switch>
然后在 Show 组件中
class Show extends React.Component {
componentDidMount() {
const {shows, match} = this.props;
const {params} = match;
// get the data from shows which matches params.id here using `find` or `filter` or whatever you feel appropriate
}
componentWillReceiveProps(nextProps) {
const {match} = this.props;
const {shows: nextShows, match: nextMatch} = nextProps;
const {params} = match;
const {params: nextParams} = nextMatch;
if( nextParams.showId !== params.showId) {
// get the data from nextProps.showId and nextShows here
}
}
}
然而,这就是图书馆喜欢的地方redux http://redux.js.org/ and reselect https://github.com/reactjs/reselect很有用。 Redux 你的数据shows
将位于一个公共商店中,您可以在任何组件中访问它,并且reselect
为您提供了创建选择器的选项,该选择器被记忆以获得适当的show
数据来自shows
,这样就不会再次重复相同的计算。请探索这些并检查您是否发现它们适合您的项目。