mapStateToProps如何在react-redux实现中接收更新的状态

时间:2016-12-19 00:25:15

标签: javascript reactjs redux react-redux immutable.js

我正在学习反应和redux实现,并遇到了一个我找不到修复的错误。 函数mapStateToProps获取初始(和空)状态。 我对状态对象使用了Seamless-Immutable,我知道我的reducer实际上是被调用并更新状态的。 我已经尝试了每个与组件道具相关的方法(componentWillReceivePropscomponentWillMountcomponentDidMount等等。)和 mapStateToProps永远不会收到更新的状态;总是初始空状态。它可以在这些方法中调用this.props.dispatch之前运行。

我一定错过了什么......

相关文件:

1。 app / index.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './index.css';
import PlaylistList from '../../components/PlaylistList';
import { fetchPlaylists } from '../../store/playlists/actions';
import { getPlaylists } from '../../store/playlists/reducer';
import { connect } from 'react-redux';

class App extends Component {
  componentWillReceiveProps() {
    this.props.dispatch(fetchPlaylists();
  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to My Music Store</h2>
        </div>
        <PlaylistList playlists={this.props.playlists}></PlaylistList>
      </div>
    );
  }
}

function mapStateToProps(state) {
  console.dir(state); // prints the initial state (before reducer run)
  return {playlists: getPlaylists(state)}
}

export default connect(mapStateToProps)(App);

2。 actions.js:

import * as api from '../../services/api';
import * as types from './actionTypes';
import _keyBy from 'lodash/keyBy';

export function fetchPlaylists() {
  return async (dispatch, getState) => {
    try{
      const playlists = await api.fetchPlaylists();
      const playlistsById = _keyBy(playlists, (playlist) => playlist.id);
      dispatch( {  type: types.PLAYLISTS_FETCHED, playlistsById} );
    } catch (error) {
      console.error(error);
    }
  }
}

第3。 reducer.js:

import * as types from './actionTypes';
import _mapKeys from 'lodash/mapKeys';
import _mapValues from 'lodash/mapValues';
import Immutable from 'seamless-immutable';

const initialState = Immutable({
    playlistsById: {},
    currentPlaylist: undefined
  }
);

export default function reduce(state = initialState, action = {}){
  switch (action.type) {
    case types.PLAYLISTS_FETCHED:
      return state.merge({
        playlistsById: action.playlistsById
      })
    default: return state

  }
}

export function getPlaylists(state) {
  let playlistsById = state.playlistsById;
  let playlistIds = _mapKeys(state.playlistsById);
  console.dir({playlistsById, playlistIds}); // prints empty objects
}

4。 reducers.js:

import playlistsReducer from './playlists/reducer';

export { playlistsReducer };

5。 actionTypes.js

export const PLAYLISTS_FETCHED = 'playlists.PLAYLISTS_FETCHED';
export const PLAYLIST_ADDED = 'playlists.PLAYLIST_ADDED';
export const PLAYLIST_REMOVED = 'playlists.PLAYLIST_REMOVED';
export const PLAYLIST_UPDATED = 'playlists.PLAYLIST_UPDATED';
export const FILTER_BY_SEARCH = 'playlists.FILTER_BY_SEARCH';

6。 src / index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import App from './containers/App';
import './index.css';
import * as reducers from './store/reducers';

const store = createStore(combineReducers(reducers), applyMiddleware(thunk));

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

1 个答案:

答案 0 :(得分:2)

您的实现问题在于mapStateToProps您希望state参数引用playlistsReducer的状态,而实际上它指的是整个状态对象减少器由combineReducers函数组合而成。

州内playlistsReducer的正确路径为 - state.playlistsReducer。因此,您的mapStateToProps必须如下所示:

function mapStateToProps(state) {
  console.dir(state.playlistsReducer); // prints the initial state (before reducer run)
  return {playlists: getPlaylists(state.playlistsReducer)}
}

通过使用此mapStateToPropsgetPlaylists将收到一个包含所需数据的正确对象,以将所需的道具传递给组件。

另一个主要问题是getPlaylists方法不会返回任何内容。