react的动态路由

1. 动态路由传参 建议用这个,刷新不会丢

  history.push(`/detail/${id}`)

2 query传参

   history.push({ pathName: '/detail', query: { myid: id } })   

3. state传参

   history.push({pathname:'/detail',state:{myid: id}})    
import React, {useEffect, useState } from 'react'
import axios from 'axios'
import { NavLink,useHistory } from "react-router-dom"
export default function NowPlaying(props) {
    const [list, setlist] = useState([])
    useEffect(() => {
        axios({
            url: "https://m.maizuo.com/gateway?cityId=110100&pageNum=1&pageSize=10&type=2&k=5064519",
            hearder: {
                'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.2.0","e":"16473286284773838969634817","bc":"110100"}',
                'X-Host': 'mall.film-ticket.film.list'
            }
        }).then((res) => {
            console.log(res.data.data.films)
            setlist(res.data.data.films)
        })  
    }, [])
    const history = useHistory()
    const handleChangePage = (id) => {
    //     windows.location.href = "#/detail/" + id
    //     props.history.push(`/detail/${id}`)
    //    this.props.history.push(`/detail/${id}`)
    // 1 -动态路由传参  建议用这个,刷新不会丢
      history.push(`/detail/${id}`)
    // 2 query传参    
        // history.push({ pathName: '/detail', query: { myid: id } })   
    // 3 state传参
        // history.push({pathname:'/detail',state:{myid: id}})    
        
    }
    return (
        
{ list.map(item => { /**编程式导航 */
  • handleChangePage(item.filmId)}> {/* 声明式导航 */} {/* {item.name} */}
  • }) }
    ) }
    import React, { Component } from 'react'
    import { HashRouter, Route, Redirect,Switch } from 'react-router-dom'
    
    import Films from './../views/Films'
    import Cinemas from './../views/Cinemas'
    import Center from './../views/Center'
    import Detail from './../views/Detail'
    
    import NotFound from './../views/NotFound'
    
    
    export default class indexRouter extends Component {
      render() {
        return (
            
                {/* 插槽 */}
                {this.props.children}
                
                    
                    
                    
    
                    {/* 动态路由 */}
                    {/*  */}
                    {/* query传参 */}
                    
                    {/* */}
                    
                    {/* 精确匹配  exact*/}   
                    
                
                {/* 模糊匹配 */}
           
        )
      }
    }
    

    你可能感兴趣的:(react的动态路由)