Ern*_*Kev 5 reactjs react-redux redux-promise redux-promise-middleware
我想在我的动作生成器中添加一个 isLoading 标志并在我的减速器上重置它。最初没有标志,我的代码工作,动作如下所示
export function getList() {
const FIELD = '/comics'
let searchUrl = ROOT_URL + FIELD + '?ts=' + TS + '&apikey=' + PUBLIC_KEY + '&hash=' + HASH;
const request = axios.get(searchUrl)
return {
type: FETCH_LIST,
payload: request,
}
}
Run Code Online (Sandbox Code Playgroud)
和减速机看起来像
const INITIAL_STATE = { all: [], id: -1, isLoading: false };
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case FETCH_COMIC_LIST:
console.log('reducer action =', action, 'state =', state)
return {
...state,
all: action.payload.data.data.results,
isLoading: false
}
default:
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,对象返回正常,我可以通过 action.payload.data.data.results 获取我的列表
请注意,我使用 redux promise 作为中间件来处理 promise。
一旦我将我的操作更改为以下并重新运行代码,我将我的有效负载(如下图所示)成为一个 Promise 而不是返回的对象
export function getComicList() {
const FIELD = '/comics'
let searchUrl = ROOT_URL + FIELD + '?ts=' + TS + '&apikey=' + PUBLIC_KEY + '&hash=' + HASH;
const request = axios.get(searchUrl)
return {
type: FETCH_COMIC_LIST,
isLoading: true,
payload: request,
}
}
Run Code Online (Sandbox Code Playgroud)
为什么简单地添加另一个变量会导致这个问题??
Spe*_*gum -1
试试这个 - 它是如何使用 redux-thunk 完成的 - 所以我希望它与 redux-promise-middleware 类似。另请参阅从以下位置返回的内容:
all: action.payload在你的减速机中
export function getList() {
const FIELD = '/comics'
let searchUrl = ROOT_URL + FIELD + '?ts=' + TS + '&apikey=' + PUBLIC_KEY + '&hash=' + HASH;
// return a promise that the middleware should handle
// return response or error from promise
return axios.get(url)
.then((response) => {
type: FETCH_LIST,
isLoading: true,
payload: response
}).error((response) => {
//handle error
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1009 次 |
| 最近记录: |