react router 父子路由如何通信

问题描述

应该是父组件和子路由<Route>的通信问题:
Home 组件中有一个子<Route>指向city组件,如果让子<Route>里的方法更改 Home 组件的 state?

如果不用 redux 之类的状态管理工具可以实现吗?

相关代码

// Home 组件
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link, withRouter } from "react-router-dom";
import { fpost } from '../../assets/lib/fetch'
import api from '../../assets/utils/api'
import './Home.scss'

import City from '../city/City'

class Home extends Component {
    constructor(props) {
        super(props);
        
        this.state = {
            date: new Date(),
            searchDay: '2019-02-12', 
            showDay: '02月12日', 
            depCity: { //出发
                name: '上海',
                showName: '上海',
                station: ''
            },
            desCity: { //到达
                name: '苏州',
                showName: '苏州',
                station: ''
            }
        };
    }
    
    //进入城市选择出发城市
    btnChoseDep = () => {
        this.props.history.push("/index/city");
    }

    //进入城市选择到达城市
    btnChoseDes = () => {
        this.props.history.push({
            pathname : '/index/city',
            state : {
                cname: this.state.depCity.name,
                cid: this.state.depCity.id
            }
        })
    }

    render() {
        return (
            <div className="Home">
                {/* 出发城市、到达城市 */}
                <section className="cityArea flex_box flex_align_center">
                    <dl className="depture flex_1">
                        <dt>出发城市/车站</dt>
                        <dd onClick={this.btnChoseDep}>{this.state.depCity.showName + this.state.depCity.station}</dd>
                    </dl>
                    <span className="exchange iconf color">&#xe62c;</span>
                    <dl className="destination flex_1">
                        <dt className="r">到达城市/车站</dt>
                        <dd onClick={this.btnChoseDes} className="r">{this.state.desCity.showName + this.state.desCity.station}</dd>
                    </dl>
                </section>
                
                {/* 嵌套路由 City组件 */}
                <Route path={`${this.props.match.path}/city`} component={City}></Route>
            </div>
        );
    }
}

export default withRouter(Home);
阅读 4.6k
2 个回答

可以吧,在Home里写一个方法,然后通过

    this.props.history.push({
        pathname : '/index/city',
        state : {
            func: func, //方法
            
        }
    })

或者在Route的时候传进去

<Route 
    path={`${this.props.match.path}/city`} 
    render={props => <City {...props} func={this.func}
/>></Route>

前提是Home不卸载,我看你代码应该也不会卸载

不能!!!!!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题