在React Native Redux中发现存储未找到错误

时间:2018-08-10 08:52:06

标签: react-native redux react-redux

我的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 个答案:

答案 0 :(得分:0)

您的方法几乎是正确的,但仍需要调整。问题是因为connect试图找到redux存储实例,但没有参考。

您需要移动connect并包装子组件而不是根。

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;