1. 程式人生 > >react路由傳參獲取後臺資料

react路由傳參獲取後臺資料

前期準備工作:

1. npm  install  axios   (axios  用來獲取資料用)   下載完成後可以console.log(axios); 驗證是否下載成功

2. data.js (模擬後臺資料,相當於後臺介面)

import React, { Component } from 'react';import { BrowserRouter as Router, Route, Link } from 'react-router-dom';import axios from 'axios';import Data from './data.js';
class Article extends
Component { constructor() { super(); this.state = { content: '', } } componentDidMount() { this.getData(); } getData() { const url = Data; axios.get(url).then( res => { if(this.props.match.params.id == '1'){ this.setState({ content : res[0].content, }) }else
if(this.props.match.params.id == '2') { this.setState({ content : res[1].content, }) }else{ this.setState({ content : res[2].content, }) } }); } render() { return( <div>{this.state.content}</div> ); }}class App extends
Component { render() { return ( <div className="App"> <Router> <div> <Link to='/article/1'>test01</Link><br /> <Link to='/artlcle/2'>test02</Link><br /> <Link to='/article/3'>test03</Link> <Route path='/article/:id' component={Article} /> {/* 相當於路由 */} </div> </Router> </div> ); }}
export default App;

data.js

const objContent = [{ id: '1', content: '001'},{ id: '2', content: '002'},{ id: '3', content: '003'}];console.log(objContent);