无法从Redux商店获得价值

时间:2018-02-03 22:40:34

标签: reactjs redux react-redux

我在从Redux商店检索数据时遇到问题。 Redux记录器正在显示数据,但似乎无法呈现它。下面是我的容器组件和我的action / reducer的代码:

//COMPONENT:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchGrade } from '../../modules/smiles';

class Main extends Component {
  componentDidMount() {
    this.props.fetchSmile();
    console.log(this.props);
  }

  render() {
    const { smiles } = this.props;
    return (
      <div>
        <h1>This is the Main Component</h1>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return { smiles: state.smiles };
};

const mapDispatchToProps = dispatch => {
  return {
    fetchSmile: params => dispatch(fetchGrade(params))
  };
};

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

//ACTION/REDUCER:
import axios from 'axios';
const ADD_GRADE = 'SMILES/ADD_GRADE';

export function reducer(state = {}, action) {
  switch (action.type) {
    case ADD_GRADE:
      return {
        ...state,
        grade: action.payload
      };

    default:
      return state;
  }
}

export const fetchGrade = () => {
  return dispatch => {
    axios
      .get('/api/test')
      .then(res => dispatch({ type: ADD_GRADE, payload: res.data }));
  };
};

//STORE:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import logger from 'redux-logger';
import reducer from '../modules';

let store;

export function configureStore(state: {}) {
  if (!store) {
    store = createStore(
      reducer,
      state,
      composeWithDevTools(applyMiddleware(logger, thunk))
    );
  }

  return store;
}

//INDEX.JS:
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';

import './index.css';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
import { configureStore } from './store';

window.store = configureStore();

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

registerServiceWorker();

我真的不知道这是复杂还是容易解决。我觉得我做得很对,但没有运气。

1 个答案:

答案 0 :(得分:1)

您将缩减器命名为reducer

export function reducer(state = {}, action) {

似乎您忘记从reducer对象访问它。它应该是这样的:

const mapStateToProps = state => {
  return { smiles: state.reducer.smiles };
};