将数据从子路由传递到父路径

时间:2017-03-30 19:57:23

标签: reactjs react-router react-redux

我有这样的路线结构:

        <Route path="/master" component={MasterPageLayout}>
            <IndexRoute path="/master/products" component={ProductsPage}/>
            <Route path="/master/customer/:id" component={CustomerDetailsPage}/>
            <Route path="/master/product/:id" component={ProductDetailsPage}/>
            <Route path="/master/price-table" component={PriceTablePage} />
        </Route>
        <Route path="/poc" component={DistribuitorPageLayout}>
            <IndexRoute path="/poc/inventory" component={InventoryPage}/>
        </Route>

MasterPageLayout里面我有我的标题和我的侧边菜单(对于他上面的所有嵌套路线都是通用的),props.children会在这些菜单结构中呈现,但我的标题有一个特定的文本路线。如何将文本(以及其他一些数据)从孩子传递给父亲?

1 个答案:

答案 0 :(得分:1)

将数据传回树中通常会使用回调进行处理。因为您只需要获取值,我建议您使用其中一个mounting lifecycle methods来调用回调。

当您标记react-redux时,我会举例说明React和Redux。我不相信基本的反应示例实际上适合您的情况,因为您渲染props.children会使回调传递更加困难,但我会将其留在答案中以防万一#39;对其他人有用。 redux示例应该适用于您的问题。

基本反应

您可以将回调传递给子组件,该子组件在组件状态中设置值以在呈现时使用

class Child extends React.Component {
    componentWillMount() {
        this.props.setText("for example")
    }

    render() {
        return (
            <div>whatever</div>
        )
    }
}

class Parent extends React.Component {
    render() {
        return (
            <div>
                <Child setText={(text) => this.setState({text})} />
                {this.state.text}
            </div>
        )
    }
}

阵营/终极版

您可以调度操作以在装入子项时设置文本,该子项在商店中设置要在父项中呈现的值,例如

class ChildView extends React.Component {
    componentWillMount() {
        this.props.setText("for example")
    }

    render() {
        return (
            <div>whatever</div>
        )
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        setText: (text) => dispatch(setParentText(text))
    }
}

const Child = connect(null, mapDispatchToProps)(ChildView)

const ParentView = ({ text }) => {
    return (
        <div>
            <Child />
            {text}
        </div>
    )
}

const mapStateToProps = (state) => {
    return {
        text: state.parent.text
    }
}

const Parent = connect(mapStateToProps)(ParentView)

我不会担心显示动作创建者和减速器/商店设置。如果您正在使用redux,那么您应该能够找出该位。

如果Parent没有直接呈现Child,无论是通过props.children还是引入了额外的图层,此方法也会有效。事实上,只要两个事件都在同一页面上呈现,Parent事件就不需要成为Child的祖先,只要两者都在同一页面上呈现。

相关问题