How to create new elements with a React mapping repository

I am trying to create elements with React dynamically, but I cannot use it correctly this.props. I currently have no new items. I tried looking at other answers and imitating them, but without any luck.

React.createClass({
getDefaultProps: function() {
    var items = [];
    chrome.storage.local.get(null, function(result) {
        var keys = Object.keys(result);
        // get all the keys from chrome storage and add to array items
        for (var i = 0; i < keys.length; i++) {
            items.push(keys[i]);
        }
    })
    return {
        items: items
    }
},
render: function() {
    // display an element with name of key
    return (
        <div>
        {this.props.items.map(function loop(item, i) {
            return (<div>{item}</div>)
        })}
        </div>
    )
}
})

However, when I substitute a literal array for this.props.items, I get new elements. Any ideas what I'm missing here?

+4
source share
1 answer

chrome.storage is asynchronous:

It is asynchronous with bulk read and write operations, and therefore faster than the blocking and sequential LocalStorage APIs.

, getDefaultProps , - { items: [] }. , "componentDidMount" :

React.createClass({

    getDefaultProps: function() {
        return {
            items: [] // initial is empty
        }
    },

    componentDidMount: function() { // the component has be rendered for the 1st time
        chrome.storage.local.get(null, function(result) { // receive the items
            var keys = Object.keys(result);
            // get all the keys from chrome storage and add to array items
            for (var i = 0; i < keys.length; i++) {
                items.push(keys[i]);
            }

            this.setState({ items: items }); // set the state
        }.bind(this)) // bind the callback to the component this, so you can use this.setState
    },

    render: function() {
        // display an element with name of key
        return (
            <div>
            {this.props.items.map(function loop(item, i) {
                return (<div>{item}</div>)
            })}
            </div>
        )
    }

})
+4

Source: https://habr.com/ru/post/1650740/


All Articles