代码之家  ›  专栏  ›  技术社区  ›  Luke

React Redux渲染连接组件

  •  0
  • Luke  · 技术社区  · 7 年前

    我正在使用 connect 函数React-Redux将我的商店连接到React组件。连接后,我想渲染组件。这项工作:

    class Init extends React.Component {
      render() {
        return (
          <View /> // Is really more elaborate
        )
      }
    }
    

    将其连接到商店:

    const InitPage = connect(
      state => ({
      }),
      dispatch => ({
      })
    )(Init)
    

    现在渲染它:

    class App extends React.Component {
      render() {
        const content = <InitPage />
    
        return (
          {content}
        )
      }
    }
    

    太棒了这一切都有效。然而

    当我放置 连接 在函数内部返回connect,如:

    const getInitPage = () => {
      const InitPage = connect(
        state => ({
        }),
        dispatch => ({
        })
      )(Init)
    
      return InitPage
    }
    

    如果现在尝试渲染组件:

    class App extends React.Component {
      render() {
        const content = getInitPage()
    
        return (
          {content}
        )
      }
    }
    

    我收到一个错误:

    Invariant Violation: React.Children.only expected to receive a single React element child.
    

    从函数返回Redux“已连接”组件的正确方法是什么?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Shubham Khatri    7 年前

    如果要从函数返回组件,则需要按如下方式渲染它

    class App extends React.Component {
      render() {
        const Content = getInitPage()
    
        return (
          <Content/>
        )
      }
    }
    

    还要确保componentName以大写字符开头。