反应路由器显示数据

时间:2017-10-11 01:30:26

标签: reactjs react-router router

我正在尝试使用反应路由器,但我遇到了麻烦。当我点击链接时,我希望它消失以前的数据,只显示当前数据。但在我的情况下,它似乎两个数据,我也无法通过网址访问。有人能帮助我吗?

我正在尝试使用反应路由器,但我遇到了麻烦。当我点击链接时,我希望它消失以前的数据,只显示当前数据。但在我的情况下,它似乎两个数据,我也无法通过网址访问。有人能帮助我吗?

我的代码:

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>   
    )
     

}

1 个答案:

答案 0 :(得分:1)

您只需要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>);
}

编辑:收到评论后修正了代码中的错误。