简体   繁体   中英

How would I map over a state on render in react?

I'm trying to learn about react and have a little issue.
When I try to map over a state of array, I get "Cannot read property 'map' of null".
How would I make sure the state is set before I render?

state = {
    array: []
};

componentDidMount() {
    this.setState({ array: JSON.parse(localStorage.getItem('session')) });
}

render() {
    const displayArray = this.state.array.map((item, index) => {
        return <p key={index}>{item}</p>
    });
    return (
        <div>{displayArray}</div>
    );
}

If there is no stored value in local storage for the key 'session' , you'll get back null . Passing that into JSON.parse , it will be converted to "null" and then parsed (giving null again). You're then using that as your array value.

To handle that case, provide a default for when the key isn't there:

this.setState({ array: JSON.parse(localStorage.getItem('session')) || [] });
// ---------------------------------------------------------------^^^^^^

That still assumes that if there's a value stored, it will parse to an array. If it's possible a non-array value has been stored, you'll need a more comprehensive check:

let array;
try {
    array = JSON.parse(localStorage.getItem('session'));
} catch (e) {
}
this.setState({array: Array.isArray(array) ? array : []});

...or similar.


Side note: Since retrieving from local storage is synchronous, there's no need to wait until componentDidMount to do it. Just do it when creating your state initially:

state = {
    array: JSON.parse(localStorage.getItem('session')) || []
};

(Again, doing the more comprehensive check if necessary.)

If it were asynchronous, you'd want to wait, but since it's synchronous, there's no need and doing it earlier avoids an unnecessary render.


Side note 2: See the documentation on keys for why using the index as the key is generally not recommended:

We don't recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny's article for an in-depth explanation on the negative impacts of using an index as a key . If you choose not to assign an explicit key to list items then React will default to using indexes as keys.

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