1. 程式人生 > >React 學習筆記 (八)(react-router 4. 頁面傳值)

React 學習筆記 (八)(react-router 4. 頁面傳值)

動態路由傳值

1.配置(根元件載入元件,注意path寫法: /xxx/:id)

<Route path='/product/:id' component={RouterProduct}></Route>

2.跳轉(注意寫法:es6 模板字串 鍵盤esc下面的按鈕 不是單引號)

<Link to={`/product/${val.id}`}>{val.title}</Link>

3.獲取值
this.props.match.params.id

生命週期函式中this.props 返回的資料
在這裡插入圖片描述
商品列表.js

import React, { Component } from 'react';
import {Link} from 'react-router-dom';//先引用Link 才能使用Link 進行跳轉
class RouterNews extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            list:[
                {
                    id:'1',
                    title:'商品111'
                },
                {
                    id:'2',
                    title:'商品222'
                },
                {
                    id:'3',
                    title:'商品333'
                },
                {
                    id:'4',
                    title:'商品444'
                },
            ],
         };
    }
    render() {
        return (
            <div>
                <h2>商品</h2>
                <ul>
                    {
                        this.state.list.map((val,key)=>{
                            return (
                            <li key={key}>
                            {/* es6 模板字串 鍵盤esc下面的按鈕 不是單引號*/}
                                <Link to={`/product/${val.id}`}>{val.title}</Link>
                            </li>
                            )
                        })
                    }
                </ul>
            </div>
        );
    }
}
export default RouterNews;

商品詳情.js

import React, { Component } from 'react';
class RouterProduct extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            id:''
         };
    }
    // 獲取動態路由
    // 生命週期函式中獲取
    componentDidMount(){
        console.log(this.props)
        this.setState({
            id:this.props.match.params.id
        })
    }
    render() {
        return (
            <div>
                <h3>商品詳情{this.state.id}</h3>
            </div>
        );
    }
}
export default RouterProduct;