简体   繁体   中英

Rendering redux props map is not a function

I'm trying to render out a redux state by mapping through an array of objects but I'm getting map is not a function. I can console.log my props to see it is receiving but it looks as though it's trying to map through it before the props have been passed into the component. As you can see I've tried also using the && method as others have suggested but all I get back is:

TypeError: myItems.map is not a function

Here's the code I have

import React, {Component} from 'react';
import { connect } from 'react-redux';

class RandomComponent extends Component {
    state = {
        myItems: this.props.myItems
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        console.log('Styles: ', this.props.myItems); // Returns object array 
    }

    render() {
        const {myItems} = this.props; // also tried this.state
        return (
            <ul>
               {myItems && myItems.map((item) => {
                    return <span>Hello.</span>
                })}
            </ul>
        );
    }
}

const mapStateToProps = state => ({
    myItems: state.getmyItems.myItems
});

export default connect(mapStateToProps)(RandomComponent);

Your initialState is an object, set it to an empty array []. In your catch return an empty array and not an empty object. The && does not work because an empty object "exists". If u still want to use the && then set initialState to undefined

map is a function for arrays your data type might be an object . To iterate over an object you can use for... in

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM