不变违规:在“连接(登录)”的上下文中找不到“商店”

Invariant Violation: Could not find “store” in the context of “Connect(Login)”

最近开始学习react-native和redux。第一次尝试 redux 时,我使用了一个在线教程来在我已经使用 react-native 创建的基本登录屏幕中实现 redux。

我使用了一个值为 0 的示例状态,它实际上没有做任何事情。我想通过稍后更改它的值来解决它。在我将 export default Login 更改为 Export default connect(myStateToProps)(Login) 和我收到以下错误-

Invariant Error

这是登录屏幕代码:

import {Button, StyleSheet, View, Text, TextInput, Alert} from 'react-native';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import {createStore} from 'redux';
import {Provider, connect} from 'react-redux';

const iniState = {
  example: 0
}

const reducer = (state = iniState) => {
  return state
}

const store = createStore(reducer)


export class Login extends Component {
  state = {username: '', password: ''};

  checkLogin() {
    const {username, password} = this.state;
    if (username == 'naman' && password == 'naman') {
      this.props.navigation.navigate('calculator');
    } else {
      Alert.alert('Login Failed', 'Incorrect Username or Password', [
        {
          text: 'Okay',
        },
      ]);
    }
  }
  render() {
    return (
    <Provider store={store}>
      <View style={styles.container}>
        <Text style={styles.heading}>Naman's Calculator</Text>
        <TextInput
          style={styles.input}
          underlineColorAndroid="black"
          placeholder="Username"
          onChangeText={text => this.setState({username: text})}
        />
        <TextInput
          style={styles.input}
          secureTextEntry={true}
          underlineColorAndroid="black"
          placeholder="Password"
          onChangeText={text => this.setState({password: text})}
        />
        <Button title={'Login'} onPress={_ => this.checkLogin()} />
      </View>
    </Provider>
    );
  }
}

function mapStateToProps(state){
  return {
    example: state.example
  }
}

export default connect(mapStateToProps)(Login);


const styles = StyleSheet.create({
  heading: {
    fontSize: 25,
    textAlign: 'center',
  },
  input: {
    marginLeft: 20,
    marginRight: 20,
    padding: 20,
  },
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#72DC8C'
  },
});

此登录屏幕随后导出到 App.js,如下所示:

import {Platform, StyleSheet, View, Text} from 'react-native';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import Calculator from './Calculator';
import Login from './Login';

const AppNavigation = createStackNavigator({
  login: Login,
  calculator: Calculator,
});

export default createAppContainer(AppNavigation);

任何帮助将不胜感激!

这将不起作用,因为您在与 connect() 相同的组件上使用 <Provider /> 组件。发生的事情是:connect 正在用 redux 包装器包装您的组件,而 <Provider /> 在 redux 包装器内。但是 <Provider /> 总是需要在任何 redux 包装器组件之上。

您需要创建一个新组件,例如 <App />,将您的商店放在那里,然后在 <App /> 下方添加登录信息。