REACT / REDUX:如何将Store连接到App组件?

时间:2019-08-21 15:19:07

标签: reactjs redux

如果可能的话,我想在不创建其他文件的情况下使我的主要组件处于状态,这是我的代码:

import React from 'react';
import { Provider } from 'react-redux';
import { connect } from 'react-redux';
import store from './store';

const App = ({ isAuthenticated }) => {
    return (
        <Provider store={store}>
            {isAuthenticated ? (
                <>
                    <p>...AUTHED...</p>
                </>
            ) : (
                <>
                    <p>...NOT AUTHED...</p>
                </>
            )}
        </Provider>
    );
};

const mapStateToProps = state => ({
    isAuthenticated: state.mode.isAuthenticated
});

export default connect(mapStateToProps)(App);

我收到错误消息: “在“ Connect(App)”的上下文中找不到“存储”。要么将根组件包装在中,要么将自定义React上下文提供程序传递给和,在连接选项中将上下文使用者转换为Connect(App)。“

我尝试更改代码,但是没有用

import React from 'react';
import { Provider } from 'react-redux';
import { connect } from 'react-redux';
import store from './store';

const AppWithStore = () => {
    return (
        <Provider store={store}>
            <App />
        </Provider>
    );
};

const App = ({ isAuthenticated }) => {
    return (
        <>
            {isAuthenticated ? (
                <>
                    <p>...AUTHED...</p>
                </>
            ) : (
                <>
                    <p>...NOT AUTHED...</p>
                </>
            )}
        </>
    );
};

const mapStateToProps = state => ({
    isAuthenticated: state.mode.isAuthenticated
});

export default connect(mapStateToProps)(AppWithStore);

我想念什么吗?

1 个答案:

答案 0 :(得分:3)

Provider“使redux存储可用于任何嵌套组件。” -https://react-redux.js.org/api/provider#overview

您不想将您的组件与Provider(AppWithStore)“连接”,您想将“ Provider(App)的任何子级“连接”

根据您的第二个示例:

您需要connect的{​​{1}}组件,而不是App

AppWithStore

然后确保您默认导出connect(mapStateToProps)(App);

AppWithStore