ReactJS-动态路线

时间:2019-06-25 10:12:19

标签: reactjs react-router-dom

我有这些组成部分。我想将每个<House/>变成一个动态网址。例如,在浏览器中访问时,http://localhost:3000/houses/house/1 我想出现1号房。

应用程序中的其他内容运行正常。我只想解决实现动态路由的问题。

路由器组件

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

import App from './App'   
import Houses from './Houses'    

export default props => (
  <Router>
    <Route exact path='/' render={() => <App />} >       
      <Route exact path='/houses' render={() => <Houses />} />
    </Route>
  </Router>
)

房屋组件

import React, { Component } from 'react'
import House from './House'

var data = require('./db.json');

class Houses extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentHouse: []
    };
  }

  componentDidMount() {
    this.setState({    
      currentHouse: data[0]    
    })
  }

  render() {
    const {currentHouse} =  this.state;           
    return (
      <div className="content house">     
        <ul>
        {currentHouse.photos && currentHouse.photos.map((photo, index) => {
          return(
           <House photo={photo} key={index}/>
          )
        })}
      </ul>
      </div>
    )
  }
}

export default Houses

房屋组件

import React from 'react';

function House(prop) {
  return (
    <li><img src={`/images/${prop.photo}`}/></li>
  );
}

export default House;

1 个答案:

答案 0 :(得分:3)

<Route exact path='/houses/:id' render={(props) => <House {...props} />} />

在内部组件中检索ID:

prop.match.params.id

参考:https://scotch.io/courses/using-react-router-4/route-params