反应地图功能

时间:2021-01-19 13:56:26

标签: javascript reactjs

我正在开发一个 React 应用程序,但以下代码片段中的地图函数向我抛出了 this.props.books.map 不是函数错误。我已经包含了所有相应的代码。

我检查了控制台日志,打印的值是一个空数组?为什么会这样?

我已经检查了调度函数中的 res.data,但在那里没问题。

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
        }))
}

bookReducer

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)

1 个答案:

答案 0 :(得分:0)

您的初始状态是一个空对象而不是一个空数组,因此不能在初始化渲染时mapped