react中路由跳轉模組和引數攜帶和兄弟元件之間通訊
阿新 • • 發佈:2021-01-18
1.
//路由元件傳遞params元件 import React, { Component } from 'react' import Public from 'pubsub-js' export default class index extends Component { state = { msg: "" } componentDidMount() { Public.subscribe('MYHello', (e) => { console.log(e) this.setState({ msg: e }) }) } render() { return ( <div> 元件傳值 </div> ) } } import React, { Component } from 'react' import Header from './Headers/index' import './index.css' import axios from 'axios' import List from './list' import PubSub from 'pubsub-js' import { NavLink, Route, Switch } from 'react-router-dom' export class WeCome extends Component { send = () => { PubSub.publish('MYHello', '你好啊大兄弟') // axios.get('').then((res)=>{ // }).catch((error)=>{ // return Promise.reject(error) // }) } render() { return ( <div className="todolist-contriner"> {/* 設施路由對映關係 */} <NavLink to="/toList"> 點選 </NavLink> <div > {/* 註冊路由元件 */} <Switch> <Route path="/toList" component={List}> </Route> </Switch> </div> </div>) } } //巢狀解構和路由接受引數 import React, { Component } from 'react' import Public from 'pubsub-js' export default class index extends Component { state = { msg: "" } componentDidMount() { Public.subscribe('MYHello', (e) => { console.log(e) this.setState({ msg: e }) }) } render() { // console.log(th) const { match: { params: { id, title } } } = this.props; console.log(id) return ( <div> id:-----{id},title:---{title} 元件傳值 </div> ) } }
//search方式傳遞:
import React, { Component } from 'react' import Public from 'pubsub-js' import qs from 'querystring' //react 自帶轉換的庫所謂的search方法也就是以問好的方式拼接的引數 export default class index extends Component { state = { msg: "" } componentDidMount() { Public.subscribe('MYHello', (e) => { console.log(e) this.setState({ msg: e }) }) } render() { // console.log(th) // const { match: { params: { id, title } } } = this.props; console.log(this.props) const {location:{search}}=this.props const {id}=qs.parse(search.slice(1)) return ( <div> {/* id:-----{id},title:---{title} */} 元件傳值 id---{id} </div> ) } }
state方式傳遞引數:
const {location:{state:{id}}}=this.props // const {id}=qs.parse(search.slice(1)) return ( <div> {/* id:-----{id},title:---{title} */} 元件傳值 id---{id} </div> ) //接受引數的方式 //傳送引數的方式 <NavLink to={{pathname:"/toList",state:{id:123}}}> </NavLink>