在mapStateToProps中未定义Redux状态,找不到问题

时间:2019-02-21 05:59:18

标签: reactjs

我找不到我的错误。我在stackoverflow中尝试了很多答案,但是这些问题对我没有用。

这是我的减速机: IcmWebReducer.js

    const initialState = {
    invoices : [],
    params: {
        status: 'Pending',
        _sort: 'documentInfo.dueDate',
        _order: 'desc',
        q: ''
     }
    };

    const IcmWebReducer = (state = initialState, action) =>{
    switch (action.type){
        case 'UPDATE_INVOICES':
            return Object.assign({}, state, {
                invoices: action.invoices
            });
        case 'UPDATE_PARAMS':
            return Object.assign({}, state, {
                params: action.params
            });
        default:
            return state;
    }
   };

export default IcmWebReducer;

这是我的 App.js

import React, {Component} from 'react';
import './App.scss';

import Header from './components/header/Header'
import InvoiceAudit from "./components/invoice/InvoiceAudit";

class App extends Component {
  render() {
    return (
        <div className="App container">
            <Header/>
         /*   <InvoiceAudit store = {this.props.store}/> */
            <InvoiceAudit/>
        </div>
    );
 } 
}

export default App;

这是 index.js

import { Provider } from 'react-redux';
import { createStore } from 'redux';
import IcmWebReducer from "./reducers/IcmWebReducer";

let store = createStore(IcmWebReducer);

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

这是我正在使用mapStateToProps方法的类

    const mapStateToProps = (state) => {
    console.log(state);
    return {
        invoices: state.IcmWebReducer,
    }
};

这显示我在console.log中未定义。但我找不到错误。我也在我的减速器中返回默认状态。谁能帮助我

2 个答案:

答案 0 :(得分:0)

导出应用程序时,您应该使用connect;

export default connect(mapStateToProps)(App)

这可能有助于解决您的问题;

const ConnectedApp = connect(mapStateToProps)(App);

index.js中;

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

在您的mapStateToProps中,就足够了

const mapStateToProps = (state) => {
console.log(state);
return {
    invoices: state.invoices,
    //status: state.params.status -> like this
}

我认为问题可能在于您的发票状态试图获取整个reducer的初始状态,而不仅仅是发票空数组。

答案 1 :(得分:0)

您的App组件应使用connect方法

应用程序组件应类似于以下代码段

import React, {Component} from 'react';
import {connect} from "react-redux";
import './App.scss';

import Header from './components/header/Header'
import InvoiceAudit from "./components/invoice/InvoiceAudit";

class App extends Component {
  render() {
    return (
        <div className="App container">
            <Header/>
            <InvoiceAudit/>
        </div>
    );
 } 
}

const mapStateToProps = state => ({invoices: state.IcmWebReducer});

export default connect(mapStateToProps)(App);