【问题标题】:Fetch API in react-native using redux使用 redux 在 react-native 中获取 API
【发布时间】:2019-07-15 02:13:21
【问题描述】:

我已经用 react-native 开始了 redux。我正在尝试使用地图从列出该数据的 API 中获取数据。以下是我从 API 获取数据的代码。

App.js

const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

const App = () => {
    return (
        <Provider store={store}>  
            <ProductList />
        </Provider>
    );
};

export default App;

productList.js

class ProductList extends React.Component {
  componentDidMount() {
    this.props.dispatch(fetchProducts());
  }

  render() {
    const { products } = this.props;

    return (
      <View>
        {products.map(product => (
          <Text key={product.title}>{product.title}</Text>
        ))}
      </View>
    );
  }
}

const mapStateToProps = state => ({
  products: state.products.items,
});

export default connect(mapStateToProps)(ProductList);

productAction.js

async function getProducts() {
  return fetch("https://rallycoding.herokuapp.com/api/music_albums")
    .then(res => res.json());
}

export function fetchProducts() {
  return async dispatch => {
    return getProducts()
      .then(json => {
        dispatch(fetchProductsSuccess(json));
        return json;
      })
      .catch(error =>
        console.log(error)
      );
  };
}

export const FETCH_PRODUCTS_SUCCESS = "FETCH_PRODUCTS_SUCCESS";

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

productReducer.js

  const initialState = {
    items: [],
  };

  export default function productReducer(
    state = initialState,
    action
  ) {
    switch (action.type) {
      case FETCH_PRODUCTS_SUCCESS:
        return {
          ...state,
          items: action.payload.products
        };
      default:
        return state;
    }
  }

rootReducer.js

export default combineReducers({
  products
});

它运行良好。它也显示列表。

但是任何人都可以告诉我,如果我将在大型项目中使用这种方法是正确的方法,那么它会有用还是应该遵循其他方法?提前致谢。

【问题讨论】:

    标签: react-native redux react-redux redux-thunk


    【解决方案1】:

    我没有将 fetch 与 react-native 一起使用,但我认为这应该可以正常工作。我用过axis。而且使用方便

    import * as axios from 'axios';
    
    import Constant from './../utilities/constants';
    
    axios.defaults.baseURL = Constant.api_base_url;;
    axios.defaults.headers.post['Content-Type'] = 'application/json';
    
    // Axios interceptor for handling common HTTP errors
    // Need to use it with reducers
    axios.interceptors.response.use(res => res, err => Promise.reject(error));
    
    /**
     * HTTP request to search item in The MovieDB
     * 
     * @returns {object | Promise}
     */
    const getConfiguration = () => {
      return axios.get(`/configuration?${Constant.api_key}`)
    }
    
    export { getConfiguration }
    

    您可以查看完整代码https://github.com/SandipNirmal/React-Native-MovieDB

    【讨论】:

    • 谢谢,但我想将它与 redux 一起使用。
    • 是的,它仅使用redux 构建。我使用的是axios 而不是fetchfetch 应该适合你。
    猜你喜欢
    • 2019-02-07
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多