如何使用React映射道具创建新元素

Bri*_*han 5 javascript google-chrome reactjs

我正在尝试使用React动态创建元素,但似乎无法this.props正确使用。我目前所拥有的没有产生任何新的元素。我尝试查看各种其他答案并模仿它们,但是没有任何运气。

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>
    )
}
})
Run Code Online (Sandbox Code Playgroud)

但是,当我用文字数组代替时this.props.items,会得到新的元素。有什么想法我在这里想念的吗?

Ori*_*ori 4

chrome.storage 是异步的:

它与批量读取和写入操作异步,因此比阻塞和串行 localStorage API 更快。

这意味着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's 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>
        )
    }

})
Run Code Online (Sandbox Code Playgroud)