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

IT技术 reactjs react-router react-redux
2021-05-06 02:49:18

我有一个这样的路线结构:

        <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个回答

将数据备份到树上通常使用回调处理。因为您只需要在我建议使用其中一种安装生命周期方法来调用回调时获取该值

正如您所标记的react-redux,我将给出 React 和 Redux 的示例。我不相信基本的 react 示例实际上适合您的情况,因为您正在渲染props.children,这使得传递回调变得更加困难,但我会将其留在答案中,以防对其他人有用。redux 示例应该适用于您的问题。


基本react

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

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>
        )
    }
}

react/还原

您可以在安装子项时调度一个操作来设置文本,该操作在商店中设置一个值以在父项中呈现,例如

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这种方法的祖先