使用redux在react-native中获取API

时间:2019-02-21 08:27:58

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

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

App.js

google-api-nodejs-client

productList.js

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

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

export default App;

productAction.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);

productReducer.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 }
});

rootReducer.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;
    }
  }

运行正常。它也在显示列表。

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

1 个答案:

答案 0 :(得分:0)

我没有将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

相关问题