Редукс реквизит от вызова действия неопределен - PullRequest
0 голосов
/ 12 сентября 2018

Я пытаюсь загрузить список избранных постов, но как только я вызываю действие, чтобы получить посты, оно возвращает undefined внутри моего this.props.favourites.get ('results'), есть что-то, чего мне не хватает?или звонок, что я делаю не так?могу предоставить больше информации, если этого недостаточно

мой код указан ниже, я могу предоставить больше информации, если мне нужно

feed.js

 async componentWillMount() {
    const log = Logger.get('FeedController#componentWillMount');
    log.debug('mounting');

    // Set the options for getting the appropriate posts
    const postType = this.props.title === 'Resources' ? 'R' : 'N';

    await this.props.getCategories();
    await this.getPosts({ invalidate: true});
    await this.getFavourites();



  createFavouriteList(){
    console.log(this.props.favourites.get('results'));
    const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
    const favouriteList = this.props.favourites.get('results').toJS(); // returns undefined
    this.setState({
      dataSource: ds.cloneWithRows(favouriteList)
    });
  }

function mapStateToProps(state) {
  return {
    feed: getPosts(state),
    profile: getProfile(state),
    featuredPost: getFeaturedPost(state),
    getPostsPending: getPostsPending(state),
    categories: getCategories(state),
    favourites: getFavourites(state),
  };
}

/**
 * Creates a mapping of the actions to the properties of the connected component.
 *
 * @param {function} dispatch - Function to dispatch an action to the store
 * @return {object} Mapping of dispatchable actions
 */
function mapDispatchToProps(dispatch) {
  return {
    getPosts(options) {
      return dispatch(actions.getPosts(options));
    },
    getCategories(options) {
      return dispatch(actions.getCategories(options));
    },
    getFeaturedPost(options) {
      return dispatch(actions.getFeaturedPost(options));
    },
    getProfile() {
      return dispatch(UserActions.getProfile());
    },
    getFavourites() {
      return dispatch(favouriteActions.getFavourites());
    },
  };
}

const enhance = compose(connect(mapStateToProps, mapDispatchToProps));
export default enhance(FeedController);

Действие

// Load dependencies
import request from 'superagent';
import { API } from './../config.json';
import { getToken } from './../selectors/authentication';
import * as UserSelectors from './../selectors/user';

export const GET_FAVOURITES = {
  REQUEST: 'GET_FAVOURITES_REQUEST',
  SUCCESS: 'GET_FAVOURITES_SUCCESS',
  FAILURE: 'GET_FAVOURITES_FAILURE'
};


/**
 * Given a list of options, sends those options to the server to retrieve the list
 * of favourites.  If the request is successful
 * the posts will be added onto the list of favourites currently loaded in the
 * store.
 *
 * @param {object} [options] - Options to optionally provide to the server for the query
 *
 * @return {object} Action that is dispatched to load the favourites into the store
 */
export function getFavorites(options = {}) {
  return async function(dispatch, getState) {


    // Dispatch an action to the store to let the store know the request is taking place
    dispatch({
      type: GET_FAVOURITES.REQUEST,
      params: options
    });

    try {
      // Make the request to the server to get the list of favourites
      const { body } = await request
        .get(`${API}/favourites/all`)
        .set('Authorization', `Bearer ${getToken(getState())}`)
        .query(options);

      // Store the favourites from the server in the Redux store state
      return dispatch({
        type: GET_FAVOURITES.SUCCESS,
        meta: body.meta,
        payload: body.results
      });
    } catch ({
      response: { body }
    }) {
      // Unable to get the list of favourites from the server, store the error
      throw dispatch({
        type: GET_FAVOURITES.FAILURE,
        error: body.message
      });
    }
  };
}

Редуктор

// Load dependencies
import Immutable, { List, Map, fromJS } from 'immutable';
// import { LOGOUT } from './../actions/authentication'; TODO:
import * as actions from './../actions/favourite';

// Set the initial state
const initialState = fromJS({
  favourite: {
    meta: {},
    results: []
  },

  favourites: {
    pending: false,
    params: {
      postId: null,
      userId: null
    },
    error: null
  },

});

/**
 * Handles the management of the state for all news related actions such as
 * getting news.
 *
 * @param {object} state
 * @param {object} action
 *
 * @return {object} New state after applying the action
 */
export default function reducer(state = initialState, action) {
  switch (action.type) {
    // Get favourites request has come in, set the parameters to the store
    case actions.GET_FAVOURITES.REQUEST:
      return state
        .setIn(['getFavourites', 'pending'], true)
        .setIn(['getFavourites', 'params'], Map(action.params))
        .setIn(['getFavourites', 'error'], null);

    // Get favourites request has succeeded, save the users to the store
    case actions.GET_FAVOURITES.SUCCESS:
      return state
        .setIn(['favourites', 'meta'], Map(action.meta))
        .setIn(
          ['favourites', 'results'],
          state.getIn(['favourites', 'results']).concat(Immutable.fromJS(action.payload))
        )
        .setIn(['getFavourites', 'pending'], false);

    // Get favourites request has failed, save the error to the store
    case actions.GET_FAVOURITES.FAILURE:
      return state.setIn(['getFavourites', 'pending'], false).setIn(['getFavourites', 'error'], action.error);

    default:
      return state;
  }
}

Селектор

// Select the current list of posts with meta information
export function getFavourites(state) {
    return state.getIn(['favourite', 'favourites']);
}

export function getFavouritesPending(state) {
    return state.getIn(['favourite', 'getFavourites', 'pending']);
}

любойинформация была бы потрясающей, так как я занимаюсь этим часами, и я очень новичок в использовании избыточности Спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...