简体   繁体   中英

How can i set my state by adding storage items

I am doing a todo list project by using react and redux. I managed to send my todo's id and itself to the local storage. Now I am trying to load my storages to UI when I open the site by using componentDidMount life cycle method.

However, I can send just one of the storage items which is the last one in the storage array to my state. How can I handle this situation?

Here are my codes:

getElementsFromStorage = () => {
    let elements;

    if (localStorage.getItem('elements') === null) {
        elements = [];
    } else {
        elements = JSON.parse(localStorage.getItem('elements'))
    } return elements
}

componentDidMount() {
    const elements = this.getElementsFromStorage();

    elements.forEach(element => {
        this.setState({
            storageHolder: [...this.state.storageHolder, element]
        })
    })
}

After I did

this.setState({ storageHolder: elements })

it worked.

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