【问题标题】:Passing props from container component to nested route component将 props 从容器组件传递到嵌套路由组件
【发布时间】:2017-03-26 09:45:03
【问题描述】:

我如何在 AppContainer 和 Home 组件之间共享状态?

例如,我想将结果对象置于 AppContainer 的状态,以便将其传递给所有其他组件。

在这个应用程序中,我没有使用 Redux。

我尝试在 AppContainer 中使用 React.cloneElement 但产生错误:

元素类型无效:应为字符串(用于内置组件) 或类/函数(用于复合组件)但得到:未定义。你 可能忘记从它定义的文件中导出您的组件。

index.js

<Router history={browserHistory}>
    <AppContainer>
        <Route path="/" component={Home} />
        <Route path="search" component={Search} />
    </AppContainer>
</Router>

AppContainer.js

render() {

    return (
            <div className="containerApp">

                {this.props.children}

            </div>
    );
}

【问题讨论】:

  • 从最佳实践的角度来看,这通常不是一个好主意(尤其是因为您不使用 Redux)。您能说明您要完成的工作吗?很可能有比通过路由器传递状态更好的方法。
  • 好的。谢谢。例如,在主组件中,我有一个搜索表单并检索结果,然后将此结果添加到组件状态。但我希望这个结果出现在搜索组件中。告诉我如果我解释得更好...
  • 我认为您不能将状态从父组件传递到子组件的状态,要么使用上下文(这很麻烦),要么将状态作为道具传递给子组件。这很容易做到。为什么要把事情复杂化:P
  • 好的,我明白了。我如何将状态作为道具传递给孩子?我试过 React.cloneElement 但给我一个错误。提前致谢

标签: javascript reactjs react-router


【解决方案1】:

React.cloneElement 是正确的方法。例如:

render() {
    const childProps = {
        prop1: this.state.prop1
    }
    return (
            <div className="containerApp">

                {React.cloneElement(this.props.children, childProps)}

            </div>
    );
}

如果这给了您之前收到的错误,那么我能想到的唯一原因是 AppContainer 在任何路由匹配之前被渲染而没有任何子级。您可以通过有条件地在 AppContainer 中呈现来缓解这种情况:

render() {
    const childProps = {
        prop1: this.state.prop1
    }

    const { children } = this.props;
    return (
            <div className="containerApp">

                {children && React.cloneElement(children, childProps)}

            </div>
    );
}

【讨论】:

    猜你喜欢
    • 2018-08-28
    • 2017-08-23
    • 2017-10-14
    • 1970-01-01
    • 2019-06-20
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    相关资源
    最近更新 更多