从api提取数据到redux

时间:2018-12-07 11:57:04

标签: reactjs redux react-redux

我正在使用React并尝试通过在组件挂载时初始化fetchProducts函数来将自己的api中的数据提取到redux中。

问题是似乎分派了GET_PRODUCTS_REQUEST动作,但没有通过该动作,因此没有数据加载到redux中。

转到http://localhost:3000/product,我可以看到数据,这是正确的

如何将数据加载到redux reducer中?

component.js

componentDidMount() {
      this.props.fetchProducts()
    }   

actions.js

export function fetchProducts() {
    return async (dispatch) => {
        dispatch(fetchProductsRequest());
        const { error, response } = await fetch('http://localhost:3000/products');
        if (response) {
        dispatch(fetchProductsSuccess(response.data));
        //This is required only if you want to do something at component level
        return true;
        } else if (error) {
        dispatch(getDataFailure(error));
        //This is required only if you want to do something at component level
        return false;
        }
    };
}

export const fetchProductsRequest = () => ({
  type: FETCH_PRODUCTS_REQUEST
});

export const fetchProductsSuccess = products => ({
  type: FETCH_PRODUCTS_SUCCESS,
  payload: { products }
});

export const fetchProductsFailure = error => ({
  type: FETCH_PRODUCTS_FAILURE,
  payload: { error }
});

productsReducer.js

import {
    FETCH_PRODUCTS_REQUEST,
    FETCH_PRODUCTS_SUCCESS,
    FETCH_PRODUCTS_FAILURE
  } from '../../Constants'

  const initialState = {
    items: [],
    loading: false,
    error: null
  };

  export default function productReducer(state = initialState, action) {
    switch(action.type) {
      case FETCH_PRODUCTS_REQUEST:
        return {
          ...state,
          loading: true,
          error: null
        };

      case FETCH_PRODUCTS_SUCCESS:
        return {
          ...state,
          loading: false,
          items: action.payload.products
        };

      case FETCH_PRODUCTS_FAILURE:
        return {
          ...state,
          loading: false,
          error: action.payload.error,
          items: []
        };

      default:
        return state;
    }
  }

1 个答案:

答案 0 :(得分:0)

private val createDefaultSourceDirectorySet: (name: String?, resolver: FileResolver?) -> SourceDirectorySet = run {
    val klass = DefaultSourceDirectorySet::class.java
    val defaultConstructor = klass.constructorOrNull(String::class.java, FileResolver::class.java)

    if (defaultConstructor != null && defaultConstructor.getAnnotation(java.lang.Deprecated::class.java) == null) {
        // TODO: drop when gradle < 2.12 are obsolete
        { name, resolver -> defaultConstructor.newInstance(name, resolver) }
    } else {
        // (code omitted)
    }
}

尝试调用默认方法export function fetchProducts() { return(dispatch) => { dispatch(fetchProductsRequest()); return fetch('http://localhost:3000/products') .then(res => res.json()) .then(json => { dispatch(fetchProductsSuccess(response.data)); return json.products; }) };} 来获取异步获取中的catch响应