【问题标题】:How to create new elements with React mapping props如何使用 React 映射道具创建新元素
【发布时间】:2016-12-16 04:54:56
【问题描述】:

我正在尝试使用 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 时,我得到了新元素。任何想法我在这里缺少什么?

【问题讨论】:

    标签: javascript google-chrome reactjs


    【解决方案1】:

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

    【讨论】:

    • 如果我在 getInitialState 中定义项目,并在渲染函数中使用 this.state.items.map,这将非常有效。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2023-03-20
    • 2020-06-14
    • 2020-09-14
    • 1970-01-01
    相关资源
    最近更新 更多