现在,我正在使用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!!
那这里怎么了?
答案 0 :(得分:2)
这不是直接回答您的问题,但我想指出减速器需要同步。如果您想使用redux进行异步处理,则需要包含一个异步中间件。一些受欢迎的选项是: