reactjs - 不变违规 : Could not find "store" in either the context or props of "Connect(App)"

标签 reactjs react-native redux react-redux

您好,我正在尝试在react-native应用程序中使用redux,并且收到标题中提到的错误,特别是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)" 。我不确定问题是什么,尽管我遵循了类似的线程,但到目前为止没有任何效果。

贝娄是我的 App.js 源代码

import React, { Component } from 'react';
import { Provider, connect } from 'react-redux';
import { Platform, StyleSheet, Text, View } from 'react-native';
import * as utils from './src/utils';
import store from './src/store';

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
});

class App extends React.Component {

    constructor(...args) {
        super(...args);
    }

    login({ username, password }) {

        let requestData = new FormData();

        requestData.append('username', username);
        requestData.append('password', password);

        console.log('[Login]: Attempt');
        console.log(JSON.stringify(requestData, null, 4));

        fetch('https://my-api.lab/user/login', {
            method: 'POST',
            body: requestData
        }).then(res => res.json()).then((json) => {

            console.log('[Login]: Response');
            console.log(JSON.stringify(json, null, 4));

            if (json.authenticated) {

                console.log('[Login]: Success');

                this.props.userLoginSuccess(json);

            } else {
                console.log('[Login]: Failure');
            }

        }).catch((err) => {

            console.log('[Login]: error');
            console.log(JSON.stringify(err, null, 4));

        });

    }

    componentDidMount() {

        console.log('App mounted!');

        this.login({
            username: 'asdf',
            password: 'asdf'
        });

    }

    render() {

        let username = Object.keys(this.props.user).length ? this.props.user.data.post.username : '';

        return (

            <Provider store={store}>

                <View style={styles.container}>
                    <Text style={styles.welcome}>
                        Welcome {username} to React Native!
                    </Text>
                </View>

            </Provider>

        );
    }
}

const mapStateToProps = (state) => {
    return {
        user: state.userReducer
    }
}

const mapDispatchToProps = (dispatch) => {

    return {

        userLoginSuccess: (user) => {

            dispatch({
                type: 'USER_LOGIN_SUCCESS',
                payload: user
            })

        },

        userLoginFailure: (user) => {

        }

    }

}

export default connect(mapStateToProps, mapDispatchToProps)(App);

这也是我的index.js 文件

import { AppRegistry } from 'react-native';
import App from './App';

AppRegistry.registerComponent('pushNotificationsNative', () => App);

商店

import { createStore } from 'redux';
import rootReducer from '../reducers/index.js';

const store = createStore(
    rootReducer
);

export default store;

最后是一个简单的 reducer

import deepExtend from 'deep-extend';

const initialState = {};

const userReducer = (state = initialState, action) => {

    switch (action.type) {

        case 'USER_LOGIN_SUCCESS': {
            return deepExtend({}, state, action.payload);
        }

        default: {
            return deepExtend({}, state);
        }

    }

}

export default userReducer;

最佳答案

您正在尝试访问应用程序组件中的存储,而您的提供程序驻留在其中。因此,App 并没有真正从上下文中获取存储。您需要将 App 与 Provider 包装在一起,例如

class App extends React.Component {

    constructor(...args) {
        super(...args);
    }

    login({ username, password }) {

        let requestData = new FormData();

        requestData.append('username', username);
        requestData.append('password', password);

        console.log('[Login]: Attempt');
        console.log(JSON.stringify(requestData, null, 4));

        fetch('https://my-api.lab/user/login', {
            method: 'POST',
            body: requestData
        }).then(res => res.json()).then((json) => {

            console.log('[Login]: Response');
            console.log(JSON.stringify(json, null, 4));

            if (json.authenticated) {

                console.log('[Login]: Success');

                this.props.userLoginSuccess(json);

            } else {
                console.log('[Login]: Failure');
            }

        }).catch((err) => {

            console.log('[Login]: error');
            console.log(JSON.stringify(err, null, 4));

        });

    }

    componentDidMount() {

        console.log('App mounted!');

        this.login({
            username: 'asdf',
            password: 'asdf'
        });

    }

    render() {

        let username = Object.keys(this.props.user).length ? this.props.user.data.post.username : '';

        return (
                <View style={styles.container}>
                    <Text style={styles.welcome}>
                        Welcome {username} to React Native!
                    </Text>
                </View>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        user: state.userReducer
    }
}

const mapDispatchToProps = (dispatch) => {

    return {

        userLoginSuccess: (user) => {

            dispatch({
                type: 'USER_LOGIN_SUCCESS',
                payload: user
            })

        },

        userLoginFailure: (user) => {

        }

    }

}

const ConnectedApp = connect(mapStateToProps, mapDispatchToProps)(App);

export default const Root = () => {
    <Provider store={store}><ConnectedApp/></Provider>
}

关于reactjs - 不变违规 : Could not find "store" in either the context or props of "Connect(App)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50063157/

相关文章:

reactjs - react : Prevent infinite Loop when calling context-functions in useEffect

gulp - Browserify 无法使用 babelify 转换创建 bundle (TypeError : Path must be a string.)

react-native - 如何从 react-native 项目中取消链接库

javascript - 当应用程序在后台运行时,响应 native 电源按钮长按监听器

javascript - 更新 Redux 存储时,React 组件不会重新渲染

javascript - <突变/> refetchQueries "Unknown directive "_"."

android - 使用 React-Navigation 在所有屏幕中显示组件 - React Native

javascript - 像 bufferWhen 一样工作的 react 运算符,但仅适用于最新变量

javascript - redux thunk 中的 debounce 方法

reactjs - 如何调整material-ui表格组件的行高