我正在尝试加载收藏的帖子列表,但是一旦我调用该操作以获取帖子,它就会在我的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']);
}
任何信息都会令人赞叹,因为我已经在这里待了几个小时,并且是使用redux的超级初学者!