React native 如何为redux mapStateToProps创建BaseComponent类

React native 如何为redux mapStateToProps创建BaseComponent类,react-native,redux,react-redux,React Native,Redux,React Redux,实际上,我使用的是redux,我有我想要在所有组件之间共享的loginInfo数据。一种方法是在每个组件中我都必须编写MapStateTops。但我不想在每个组件中都这样做。有没有办法让基础组件在每个组件中使用道具 代码: 如果我这样做,我会得到例外 超级表达式必须为null或函数您可以创建一个HOC容器组件并将所有数据传递给子级 在您的示例中: function withUserData(WrappedComponent) { class HOC extends React.Compone

实际上,我使用的是redux,我有我想要在所有组件之间共享的loginInfo数据。一种方法是在每个组件中我都必须编写MapStateTops。但我不想在每个组件中都这样做。有没有办法让基础组件在每个组件中使用道具

代码:

如果我这样做,我会得到例外
超级表达式必须为null或函数

您可以创建一个HOC容器组件并将所有数据传递给子级 在您的示例中:

function withUserData(WrappedComponent) {
  class HOC extends React.Component {
    render() {
      return (
        <WrappedComponent loginInfo={this.props.loginInfo} {...this.props} />
      );
    }
  }

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

  return connect(mapStateToProps)(BaseComponent);
}
然后,在您想要使用loginInfo的每个组件中,都可以这样编写

class HomeComponent extends Components {
  render() {
    return <Text>{JSON.stringify(this.props.loginInfo)}</Text>;
  }
}
export default withUserData(HomeComponent);

您在basecomponent中说我将使用UserData方法
class HomeComponent extends Components {
  render() {
    return <Text>{JSON.stringify(this.props.loginInfo)}</Text>;
  }
}
export default withUserData(HomeComponent);