将 Redux connect() 与布局组件一起使用 children 并接收道具

Using Redux connect() with Layout component being passed children and receiving props

我在连接布局组件时遇到了一些困难,因为我正在通过 children。基本上,我设置应用程序的方式是 app.js 包含提供程序、持久化门、布局和 react-navigation 导航堆栈。

到目前为止我唯一没有连接的组件是我的布局,在我开始在顶部栏上实现一些导航之前,我并不是真的需要它。现在我希望能够将 routeName 传递给 redux,以便 Layout 知道用户在哪条路线上并可以显示适当的按钮。

我尝试了一些方法,但似乎没有任何效果,如果我设法通过连接加载布局,它似乎没有从 redux store 获取路由,即使我已经确认它在 React-Native 调试器上。

app.js

export class App extends Component {
    render() {
        return (
            <Provider store={store}>
                <PersistGate loading={null} persistor={persistor}>
                    <Layout>
                        <AppWithNavigationState/>
                    </Layout>
                </PersistGate>
            </Provider>
        )
    }
}

Layout.js 这是我之前使用的。

    class Layout extends Component {

  render() {
      const currentRoute = this.props.route;
      console.log(this.props.route); ////// TESTING TO SEE IF ROUTES SHOWS. IT'S ALWAYS "UNDEFINED" DESPITE BEING IN THE STORE.
     headerButton = () => {
          if (currentRoute==='Main') { 
                return (<Icon onPress={() => navigate({routeName: "PostForm"})} style={styles.headericon} name="back"></Icon>);
            } else {
                return (<Icon style={styles.headericon} name="menu"></Icon>)
            }
        }

.......
export default ({children}) => (
    <Layout>
        {children}
    </Layout>
)

Layout.js Test (updated but still not receiving store data)

Layout.propTypes = {
    children: PropTypes.node,
    route: PropTypes.string,
    updateRoute: PropTypes.func
 };

const mapStateToProps = state => ({
    route: state.route.route
 });

const mapDispatchToProps = (dispatch) => {
    return {
        updateRoute: route => dispatch(postActions.updateRoute(route))
    }
}

const LayoutTest = ({children}) => (
    <Layout>
        {children}
    </Layout>
)


export default connect(mapStateToProps, mapDispatchToProps)(LayoutTest);

原来我什至不需要将 'children' 传递给组件。我通过更改

来渲染它
export default ({children}) => (
    <Layout>
        {children}
    </Layout>
)

export default connect(mapStateToProps, mapDispatchToProps)(Layout)

经过一些测试,发现状态实际上可以在 mapStateToProps 函数内部读取,但它没有映射到 Layout。我之所以如此困惑,是因为我真的认为我需要像以前那样将 children 传递给它。幸运的是我从来没有!