javascript - 反应地图功能
问题描述
我正在开发一个反应应用程序,但下面代码片段中的地图函数抛出我this.props.books.map
不是函数错误。我已经包含了所有相应的代码。
我检查了控制台日志,打印的值是一个空数组?为什么会这样?
我已经检查了res.data
at dispatch 功能,但那里没问题。
class Books extends Component{
static getDerivedStateFromProps = props => {
props.getBookInfo();
console.log(props.books)
}
render(){
return(
<div>
<Header/>
<Container>
<Styles>
<Row>
{
this.props.books.map((book) => {
return(
.
.
)
</Row>
</Styles>
</Container>
<Footer/>
</div>
)
}
}
const mapStateToProps = state => ({
books: state.books
})
export default connect(mapStateToProps, { getBookInfo })(Books);
获取图书信息
export const getBookInfo = () => dispatch =>{
axios.get("http://localhost:5000/books")
.then( (res) => {
return {
type: BOOK_INFO,
payload: res.data
}
})
.catch((err) => dispatch({
type: GET_ERRORS,
payload: err.data
}))
}
图书减速机
const initalState={};
export default function(state=initalState, action){
switch(action.type){
case BOOK_INFO:
return action.payload;
default:
return state;
}
}
这就是我得到的,如果我console.log
res.data
Array(3)
0: {name: "Harry Potter", author: "J.K. Rowling", price: "150", year: "2011", description: "No wear and tear excellent condition.", …}
1: {name: "One Punch Man", author: "Yusuke Murata", price: "150", year: "2009", description: "Buy the damn thing.", …}
2: {name: "Percy Jackson", author: "Rick Riordan", price: "150", year: "2015", description: "Cool.", …}
length: 3
__proto__: Array(0)
解决方案
你的初始状态是一个空对象而不是一个空数组,因此不能map
在初始化渲染
推荐阅读
- html - 在Angular中提取上下文元素
- c++ - 如何导入 C++ 20
模块? - php - 如何从php中的日期编号获取最后一个日期和下一个日期?
- javascript - lodash debouce 不是 debounce 函数被调用多次而不是一次,react hooks react native
- vue.js - 错误:无法使用 vite 找到模块 '@vue/cli-service/generator/template/src/App.vue'
- python - 如何以编程方式备份 Peewee 数据库(SqliteQueueDatabase)?
- javascript - JavaScript:如何在每个段落之后添加 iframe?
- bash - XMonad 快捷方式和 Zenity/Qt
- python - 用于二进制分类的 cnn 模型总是返回 1
- python - 当用户编写名字和姓氏框时,我希望它使用 tkinter 和 python-docx 在单元格中打印它,我该怎么做?