2017-10-11 95 views
1

我試圖使用反應路由器,但我遇到了麻煩。當我點擊鏈接時,我希望它消失以前的數據,只顯示當前的數據。但在我的情況下,它既出現數據,也無法通過網址訪問。有人能幫我嗎?反應路由器顯示數據

我試圖使用反應路由器,但我遇到了麻煩。當我點擊鏈接時,我希望它消失以前的數據,只顯示當前的數據。但在我的情況下,它既出現數據,也無法通過網址訪問。有人能幫我嗎?

我的代碼:

import React, {Component} from 'react' 
 
import axios from 'axios' 
 

 
import ShotList from './shotList' 
 

 

 
const URL = 'https://api.dribbble.com/v1/shots/' 
 
const token = 'token' 
 

 
export default class Shots extends Component{ 
 

 
    constructor(props){ 
 
     super(props) 
 
     this.state = {list: []} 
 
     
 
     this.getShots() 
 
    } 
 
    
 
    getShots(){ 
 
     axios.get(`${URL}?access_token=${token}`) 
 
     .then(resp => this.setState({...this.state, list: resp.data}))  
 
    } 
 

 
    render(){ 
 
     return(
 
      <div> 
 
       
 
       <ShotList list={this.state.list}/> 
 
       
 
       </div> 
 
     ) 
 
    } 
 
}

import React from 'react' 
 
import {BrowserRouter as Router, Route, Link} from 'react-router-dom' 
 

 
export default props =>{ 
 
    
 

 
    const renderRows =() =>{ 
 
     const list = props.list || [] 
 
     JSON.stringify(list) 
 
     return list.map(shots =>(
 
     <Router key={shots.id}> 
 
      <div > 
 
      <Link to={`/shots/${shots.id}`}> 
 
       <div className='col-md-3 col-sm-4 col-xs-6 teste'> 
 
        <img src={shots.images.normal} className='img-responsive' /> 
 
        <p>{shots.views_count}</p> 
 
       </div> 
 
       </Link> 
 
       <Route path="/shots/:shotsId" component={Detail}/> 
 
       </div> 
 
        
 
     </Router> 
 

 
     
 
     )) 
 
     
 
     
 
} 
 

 
const Detail = ({match}) =>{ 
 
    
 
    return(
 
     <div> 
 
      {match.params.shotsId} 
 
      
 
      </div> 
 
    ) 
 
    
 

 
} 
 

 
    return(
 
     <div> 
 
      {renderRows()} 
 
     </div> 
 
    ) 
 
     
 

 
}

回答

0

你只需要1 Router路由,而不是爲每個單排創建一個新的Router。您只需要使用Switch來渲染所選的Route。您的renderRows的代碼可以修改如下。

import React from 'react' 
 
import {BrowserRouter as Router, Route, Switch, Link} from 'react-router-dom' 
 

 
export default props =>{ 
 
    const renderRows =() =>{ 
 
    const list = props.list || [] 
 
    JSON.stringify(list) 
 
    return (
 
    <Router> 
 
     <div> 
 
     {list.map(shots => 
 
      <Link to={`/shots/${shots.id}`}> 
 
      <div className='col-md-3 col-sm-4 col-xs-6 teste'> 
 
       <img src={shots.images.normal} className='img-responsive' /> 
 
       <p>{shots.views_count}</p> 
 
      </div> 
 
      </Link>) }   
 
     
 
     <Switch> 
 
      {list.map(shots =><Route path="/shots/:shotsId" component={Detail}/>)} 
 
     </Switch> 
 
     </div>     
 
     </Router>); 
 
}

編輯:收到的意見,在代碼中更正錯誤後。

+0

現在顯示此錯誤
app.js:9234未捕獲錯誤:Component(...):必須返回有效的React元素(或null)。您可能返回了未定義的數組或其他無效對象。 –

+0

已更新代碼。請立即檢查。 – palsrealm

+0

我編輯了我的代碼,它錯過了一個部分,但我試圖改變它,它不工作。它與我現在放入的其他代碼有什麼關係? –