【发布时间】:2021-01-06 09:03:05
【问题描述】:
我正在从我的 API(Django REST 框架)发出 get 请求,这将返回数据(产品名称、img)。我使用 Redux-saga 作为我在 React-Native 和 Redux 中的中间件。但是,我似乎无法接收到数据。
这是我对获取请求的操作:
export function getProductList() {
type:GET_PRODUCTS_LIST
}
还有我的 api.js 文件:
const urlGetProducts = 'https://hero-pregbackend.herokuapp.com/shop/';
const urlOrderUltrascan = 'https://hero-pregbackend.herokuapp.com/ultrascan/order_scan/';
export const getProductsFromApi = function* (){
const response = yield fetch(urlGetProducts, {
method:'GET',
headers:{
'Accept':'application/json, application/xml, text/plain, text/html, *.*',
// 'Content-Type':'application/json',
},
body: '',
});
const products = yield response.status === 200 ? response.json():[]
return products;
}
export const Api = {
getProductsFromApi,
}
我的 sagas 文件:
import {GET_PRODUCTS_LIST,GET_PRODUCTS_ERROR} from '../actions/products';
import {ULTRASCAN_SUCCESS,ULTRASCAN_FAIL} from '../actions/ultrascan';
import { takeEvery, call, put, select,takeLatest} from 'redux-saga/effects';
import {Api} from './api';
function* fetchProducts(){
try {
const receivedProducts = yield Api.getProductsFromApi();
yield put({type:GET_PRODUCTS_LIST,receivedProducts:receivedProducts})
}catch(error){
yield put({type:GET_PRODUCTS_ERROR,error});
}
}
export function* productSaga(){
yield takeEvery(GET_PRODUCTS_LIST,fetchProducts);
}
我的行动减速器:
import { GET_PRODUCTS_LIST,GET_PRODUCTS_ERROR,GET_PRODUCT_DETAILS,GET_DETAILS_ERROR} from '../actions/ultrascan';
const initialState = {
productList: [],
// productDetails:[],
isFetching:false,
error:null,
};
const productsReducer = (state = initialState,action) => {
switch(action.type){
case GET_PRODUCTS_LIST:
return {
...state,
// isFetching:true,
productList:action.receivedProducts,
isFetching:false,
}
case GET_PRODUCTS_ERROR:
return {
...state,
error:action.error
}
default:
return state;
}
}
export default productsReducer;
【问题讨论】:
标签: javascript reactjs react-native redux redux-saga