根据api响应进行路由器重定向

时间:2018-12-19 03:56:51

标签: reactjs ecmascript-6 react-router-v4 react-router-dom

我正在使用tmdb api多重搜索,我有一个get请求,该请求返回一个包含对象键和值的项目数组。有些返回“ media_type:tv”,有些返回“ media_type:movie”,我为每种设置了两条不同的路线。

这里是我的App结构

<BrowserRouter>
    <div className='App'>
      <Switch>
        <Route path='/' exact component={Home} />
        {/* <Route exact path='/details/:type/:id' component={ItemDetails} /> */}
        <Route exact path='/details/movie/:id' component={MovieDetails} />
        <Route exact path='/details/tv/:id' component={TvDetails} />
      </Switch>
    </div>
  </BrowserRouter>

获取请求

` performSearch = () => { // Requesting data from API
    let now = (this.now = Date.now());
    axios.get(`${URL}api_key=${API_KEY}&language=en-US&query=${this.state.searchInput}${PARAMS}`)
        .then((res) => {
            console.log(res.data.results);
            // Accepting response if this request was the last request made
            if (now === this.now) {
               this.setState({ searchResults: res.data.results});
            }
        });
}`

呈现搜索结果项目的功能组件

    const Suggestions = (props) => {
  const options = props.searchResults.map(r => (
    <li
      key={r.id} >
      <Link key={r.id} to={`/details/${r.id}`}>
        <a href='#t' className='rating'><i className='fas fa-star fa-fw' />{r.vote_average}</a>
        <img src={`https://image.tmdb.org/t/p/w185/${r.poster_path}`} alt={r.title} className='search-results-poster' />
        <a href='#t' className='search-results-name'>{r.name}</a>
        <a href='#t' className='search-results-title'>{r.title}</a>
      </Link>
    </li>
  ))
  return <ul className='search-results'>{options}</ul>
}

我在考虑类似if(props.media_type === tv){<Redirect component={TvDetails}/> else {<Redirect component={MovieDetails}之类的东西,我是React Router的新手,所以我不确定该怎么做

我尝试了<Link key={r.id} to={ / details / $ {props.searchResults.media_type.value} / $ {r.id} }>

但是它表示值未定义,尽管我可以在console.log enter image description here

中看到它

编辑:<Link key={r.id} to={ /详细信息/ $ {r.media_type.value} / $ {r.id} }>

将我带到/ details / undefined / 1234,所以我猜该值仍然不确定吗?

2 个答案:

答案 0 :(得分:1)

media_type本身会返回您的情况下的字符串值和具有属性值的对象。因此,您只需要访问media_type而不是media_type.value

<Link key={r.id} to={`/details/${r.media_type}/${r.id}}`>

答案 1 :(得分:1)

更改
handshaker.finishHandshake(ctx.channel(), handshakeResponse); Channel channel = ctx.channel(); String extensionsHeader = handshakeResponse.headers().getAsString(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS); if (extensionsHeader == null) { // This replaces the frame decoder to make sure the rsv bits are not allowed channel.pipeline().replace(WebSocketFrameDecoder.class, "ws-decoder", new WebSocket13FrameDecoder(false, false, handshaker.maxFramePayloadLength(), false)); }

<Link key={r.id} to={/details/${r.media_type.value}/${r.id}}>
您无需添加<Link key={r.id} to={/details/${r.media_type}/${r.id}}>即可从对象中获取值