[英]Async with Redux-Saga
I'm newbie of Redux-saga. 我是Redux-saga的新手。 I have a project using Redux-saga, and this is my snip code:
我有一个使用Redux-saga的项目,这是我的代码:
// saga.js
function* FetchData() {
try {
const AppData = yield call(fetch_Data, "LOAD_APP", App_Url);
yield put({ type: "LOAD_APP", data: AppData })
} catch (error) {
console.log(error)
}
}
function* watchFetchAPI() {
yield takeEvery("LOAD_ASYNC", FetchData)
}
export default function* rootSaga() {
yield all([
watchFetchAPI()
])
}
// action.js
export function fetch_Data(type, url) {
fetch(url, {
method: 'GET',
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
contentType: 'json'
}).then(function (res) {
if (res.ok) {
return res.json();
} else {
console.log("Failed. type: " + type + " Url: " + url);
}
}).catch(function (e) {
console.log("Failed. type: " + type + " Url: " + url);
console.log(e)
})
}
In my component dispatch action : 在我的组件调度动作中:
this.props.dispatch({ type: "LOAD_ASYNC"})}
this.props.dispatch({type:“ LOAD_ASYNC”})}
And reducers : 和减速器:
// pageReducer.js
export function calc(state = [], action) {
switch (action.type) {
case "LOAD_APP":
return [{ type: action.type, data: action.data }]
default:
return state;
}
}
// rootReducer.js
import { combineReducers } from 'redux'
import { calc } from './pageReducers'
const Rootreducers = combineReducers(
{
data: calc
}
)
export default Rootreducers
I don't get data before page re-render. 重新呈现页面之前我没有数据。 I'm debug and see my api fetch return data after my page re-render , so in store data is undefined .
我正在调试,看到我的api在重新渲染页面后获取了返回数据,因此存储数据中的undefined。 How to resolve this ?
如何解决呢?
您的fetch_Data
没有返回提取结果
The problem is in fetch_Data
. 问题出在
fetch_Data
。 You should return the Promise returned by fetch
like so: 您应该返回通过
fetch
返回的Promise,如下所示:
// action.js
export function fetch_Data(type, url) {
return fetch(...).then(...).catch(...)
}
Your yield call(fetch_Data, ...)
statement will only block if a promise is returned. 您的
yield call(fetch_Data, ...)
语句仅在返回promise时才会阻塞。 Because the fetch promise is not returned, FetchData
continues on with execution and AppData
will be undefined. 由于未返回获取承诺,因此
FetchData
继续执行,并且AppData
将未定义。 By returning the promise, FetchData
will block until the promise resolved or rejected and AppData or catch will work as expected. 通过返回承诺,
FetchData
将阻塞,直到承诺被解决或拒绝,并且AppData或catch将按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.