react-router-v4 – 使用组件页面上的URL来识别和传递来自React
我正在使用React Router.在我的州,我有一些可通过身份识别识别的电视节目.在节目页面上,我需要加载特定节目的数据,将节目ID与URL的末尾相匹配.
我的州看起来像这样,但有更多的节目: shows: [ { id: 1318913 name: "Countdown" time: "14:10" },{ id: 1318914 name: "The News" time: "15:00" } ] 在App.js中: <BrowserRouter> <Switch> <Route exact path="/" render={() => { return <Table shows={this.state.shows} />; }} /> <Route path="/show/:showID" render={() => { return <Show />; }} /> <Route component={FourOhFour} /> </Switch> </BrowserRouter>; React Router在显示页面上显示URL的showID部分.所以我可以将我的整个show状态传递给Show组件,然后从url中找到正确的show.但是我想这个效率低下? 我想知道我是否应该通过App.js中的ID查看节目,并且只将正确的节目传递给Show组件.这是更好的做法/更有效吗? 这是我的表组件: class Table extends Component { render(props) { return ( <table className="table table-striped table-bordered table-hover"> <tbody> { this.props.shows.map((item)=>{ return <TableRow name={item.name} time={item.time} key={item.eppisodeId} eppisodeId={item.eppisodeId} img={item.img} /> }) } </tbody> </table> ) } } 这是我的TableRow组件: class TableRow extends Component { render(props) { const image = this.props.img !== null ? <img src={this.props.img} alt={this.props.name} /> : null; const showUrl = '/show/' + this.props.eppisodeId; return ( <tr className="tableRow"> <td className="tableRow--imgTd">{image}</td> <td><Link to={showUrl}>{this.props.name}</Link></td> <td className="tableRow--timeTd">{this.props.time}</td> </tr> ) } } 解决方法
正如我在您的问题中看到的那样,您正在使用Link进行导航.考虑到你也希望通过链接发送数据,你可以传递一个对象,而不是像
React-router docs中提到的字符串路径,所以你可以传递显示信息与TableRow组件中的状态对象一样
const {name,time,episodeId,img} = this.props; <Link to={{pathname:showUrl,state: {show: {name,img }}}}>{this.props.name}</Link> 现在,您可以在Show component中检索此信息 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> 现在上述解决方案只有在您从App中导航时才有效,但是如果您更改URL它将无法工作,如果您想使其更加健壮,您需要将数据传递给show组件然后进行优化在生命周期功能中 你会 .这样做 <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 } } } 然而,这就像 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |