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

在React Native Redux中获取store not found错误

  •  0
  • khateeb  · 技术社区  · 6 年前

    App.js 文件是:

    import React, { Component } from 'react';
    import { Provider, connect } from 'react-redux';
    import { createStore, bindActionCreators } from 'redux';
    import {Platform, StyleSheet, Text, View} from 'react-native';
    import reducers from './reducers';
    
    class App extends Component {
      render() {
    
        return (
          <Provider store={createStore(reducers)}>
            <View>
              <Text>12345</Text>
            </View>
          </Provider>
        );
      }
    }
    
    const mapStateToProps = state => {
      console.log(state);
    };
    
    export default connect(mapStateToProps)(App);
    

    Invariant Violation: Could not find "store" in either the context or props of "Connect(App)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(App)".
    

    我不知道错误在哪里。我该怎么解决?

    1 回复  |  直到 6 年前
        1
  •  0
  •   I Putu Yoga Permana    6 年前

    你的方法几乎正确,但仍然需要调整。问题是因为 connect 尝试查找redux存储实例,但没有该实例的引用。

    连接 并将子组件包装为根组件。

    import React, { Component } from 'react';
    import { Provider, connect } from 'react-redux';
    import { createStore, bindActionCreators } from 'redux';
    import {Platform, StyleSheet, Text, View} from 'react-native';
    import reducers from './reducers';
    
    const Content = (props) => (
      <View>
        <Text>12345</Text>
      </View>
    );
    
    const mapStateToProps = state => {
      console.log(state);
    };
    
    // Use connect enhancer, when the parent is wrapped with <Provider>
    const EnhancedContent = connect(mapStateToProps)(Content);
    
    class App extends Component {
      render() {
        return (
          <Provider store={createStore(reducers)}>
            <EnhancedContent />
          </Provider>
        );
      }
    }
    
    export default App;