现在,我正在使用 react 和 redux 创建一个书籍跟踪应用程序,我需要异步获取数据,现在我有 3 个版本的代码 其中两个返回预期结果,但第三个不返回
第一个:
import { FETCH_BOOKS } from '../actions/Types.js';
import * as BooksAPI from '../BooksAPI'
export const bookReducer = (state = [], action) => {
switch(action.type) {
case FETCH_BOOKS:
console.log (BooksAPI.getAll().then(books => books))
default:
return state;
}
}
//Promise {<pending>}
//this returns a promise in a pending state that is resolved to array of objects(expected)
第二个:
import { FETCH_BOOKS } from '../actions/Types.js';
import * as BooksAPI from '../BooksAPI'
export const bookReducer = (state = [], action) => {
switch(action.type) {
case FETCH_BOOKS:
console.log ([BooksAPI.getAll().then(books => books)])
default:
return state;
}
}
//[promise]
//this returns an array of a promise that is resolved to array of another array of books objects(expected)
第三个:
import { FETCH_BOOKS } from '../actions/Types.js';
import * as BooksAPI from '../BooksAPI'
export const bookReducer = (state = [], action) => {
switch(action.type) {
case FETCH_BOOKS:
console.log ([...BooksAPI.getAll().then(books => books)])
default:
return state;
}
}
//[]
//this returns an empty array, no promise
//expected spreading items of the returned array of objects not empty array!!
那么这里有什么问题??
这不是对你问题的直接回答,但我想指出化简器需要同步。如果你想用redux做异步的事情,你需要包含一个异步中间件。一些流行的选项是:
- Redux-thunk(基于承诺(
- redux-saga(基于生成器(
- redux-observable(基于可观察量(