还原状态未更新

时间:2020-05-23 18:41:21

标签: reactjs react-redux

动作:

export const fetchNewsSuccess = (article) => ({
  type: NewsActionTypes.FETCH_NEWS_SUCCESS,
  payload: article,
});
export const fetchNewsBeginAsync = () => {
  return (dispatch) => {
    const collectionRef = fireStore.collection('news');
    dispatch(fetchNewsBegin());

    collectionRef
      .get()
      .then((snapshot) => {
        dispatch(fetchNewsSuccess(snapshot));
      })
      .catch((error) => dispatch(fetchNewsFailure(error.message)));
  };
};

减速器

const newsReducer = (state = INITIAL_STATE, action) => {
  switch (action.payload) {
    case NewsActionTypes.FETCH_NEWS_BEGIN:
      return {
        ...state,
        isFetching: true,
      };
    case NewsActionTypes.FETCH_NEWS_SUCCESS:
      return {
        ...state,
        isFetching: false,
        news: action.payload,
      };
  }
}

redux-logger image

我正在尝试从Firebase数据库中获取文章数据,正在使用fuxNewsBeginAsync来获取数据(使用redux-thunk)fetchNewsBeginAsync,然后我的操作具有有效负载,但状态未更新,有人可以帮助我

1 个答案:

答案 0 :(得分:0)

呼叫collectionRef.get()将返回一个QuerySnapshot,其中包含0个或多个QueryDocumentSnapshot。您必须遍历QuerySnapshot对象中的文档,并在每个文档上调用.data()方法以提取数据。

export const fetchNewsBeginAsync = () => {
  return (dispatch) => {
    const collectionRef = fireStore.collection('news');
    dispatch(fetchNewsBegin());

    collectionRef
      .get()
      .then((querySnapshot) => {
         // extract the data first
         const results = querySnapshot.docs.map(doc => doc.data());
         // dispatch your action with results as payload
         dispatch(fetchNewsSuccess(results));
      })
      .catch((error) => dispatch(fetchNewsFailure(error.message)));
  };
};

减速器中也有错误。您应该在action.type语句中检查switch作为条件。

const newsReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case NewsActionTypes.FETCH_NEWS_BEGIN:
      return {
        ...state,
        isFetching: true,
      };
    case NewsActionTypes.FETCH_NEWS_SUCCESS:
      return {
        ...state,
        isFetching: false,
        news: action.payload,
      };
  }
}

相关问题