javascript - 如何使用 React 映射 Prop 创建新元素

标签 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>
    )
}
})

但是,当我用文字数组替换 this.props.items 时,我得到了新元素。知道我在这里遗漏了什么吗?

最佳答案

chrome.storage 是异步的:

It's asynchronous with bulk read and write operations, and therefore faster than the blocking and serial 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>
        )
    }

})

关于javascript - 如何使用 React 映射 Prop 创建新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38862684/

相关文章:

javascript - React Native图像上传文件扩展名错误

javascript - 在下拉菜单中显示图像

css - Chrome : Save custom CSS changes made in the inspector tool so they appear on page reload

javascript - 通过 ReactJS 中的 .getUserMedia 访问网络摄像头后,单击断开网络摄像头连接

javascript - 如何在 JavaScript 中限制正则表达式搜索

google-chrome - LiveSASS 启动失败

javascript - Chrome使用jquery时出现问题

javascript - ReactJS onBlur 不工作

javascript - 来自外部文件的流类型导入类型 - 名称已绑定(bind)

javascript - CSS 和 JavaScript 问题