终极版/反应。无法通过Provider在嵌套组件中获取store.getState

时间:2018-04-01 20:08:46

标签: reactjs redux react-redux

所以,我尝试了解数据流在React / Redux中是如何工作的,但我无法弄清楚如何在应用程序的嵌套组件中获取store.getState(),例如在主{{1}中} 零件。我通过App推送它,但是......

我做错了什么?

/ * INDEX.JS * /

Provider

/ * NESTED COMPONENT * /

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import TodoApp from './Reducers/TodoApp'
import App from './Components/App';
import './Styles/style.css';

const store = createStore(TodoApp);

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>, 
    document.getElementById('root')
);

2 个答案:

答案 0 :(得分:1)

在您的应用程序中包含react-redux的 Provider 组件只是您必须对代码进行的两项修改之一,以使Redux正常工作。

组件需要使用connect与REDx状态“连接”。

查看“official” example from the react-redux documentation

在你的情况下,这看起来像这样:

import React, { Fragment } from 'react';
import VisibleTodoList from '../Containers/VisibleTodoList';
import TodoFormAdd from '../Containers/TodoFormAdd';
import { connect } from 'react-redux'

class App extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        // displays the todos from the global redux stpre
        console.log(this.props.todos);
        return(
            <Fragment>
                <TodoFormAdd />
                <VisibleTodoList  />
            </Fragment>
        );
    }
}

// pick the parts of the Redux state that you want
// to use as props in your connected component
const mapStateToProps = state => ({
    todos: state.todos
});

export default connect(mapStateToProps)(App);

答案 1 :(得分:-2)

的console.log(this.props.store.getState()); //这不行 - &#34;未定义&#34;,为什么?

这是因为&#39; store&#39;不是App类的支柱

如果你想在App中将商店作为道具

尝试将代码修改为

ReactDOM.render(
    <Provider store={store}>
        <App store={store}/>
    </Provider>, 
    document.getElementById('root')
);