简体   繁体   中英

Array gets undefined in component state (React)

I have an array in a components state that I want to fill with some data from an API call. The problem is that it apparently always gets set do "undefined", and hence I cannot do any functions on it/present the data in the DOM.

This is my code right now:

class DocumentsPage extends Component {

    constructor(props) {
        super(props);
        this.state = { documents: [] };
    }

    componentDidMount() {
        this.getDocuments();
    }

    getDocuments = (e) => {
        fetch('api/GetDocuments').then(documents =>
            documents.json()).then(data => {
                this.setState({
                    documents: data
                });
            })
    }

    render() {
        return (
            <div>
                {this.state.documents.map(document => <div> {document} </div>)}
            </div>
            )
    }
} 

But I get this error when trying to present the data: "TypeError: Cannot read property 'map' of undefined". What am I doing wrong?

EDIT: I changed to this.state.documents.map, but now nothing get presented anyways, no errors either whatsoever. What am I missing?

EDIT #2: Solved it by writing the following code in the render() instead:

        return (
            <ul>
                {this.state.documents.map((document) => (
                    <li key={document.id}>{document.name}</li>))}
            </ul>
            )

Write your render like this

render() {
    return (
        <div>
            {this.state.documents && this.state.documents.map(document => <div> {document} </div>)}
        </div>
        )
}

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