Javascript 如何使用React映射道具创建新元素
我试图用React动态地创建元素,但我似乎无法正确地使用Javascript 如何使用React映射道具创建新元素,javascript,google-chrome,reactjs,Javascript,Google Chrome,Reactjs,我试图用React动态地创建元素,但我似乎无法正确地使用这个。我目前所拥有的并没有产生任何新的元素。我试过看各种其他答案并模仿它们,但没有任何运气 React.createClass({ getDefaultProps: function() { var items = []; chrome.storage.local.get(null, function(result) { var keys = Object.keys(result); // g
这个。我目前所拥有的并没有产生任何新的元素。我试过看各种其他答案并模仿它们,但没有任何运气
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>
)
}
})
React.createClass({
getDefaultProps:function(){
var项目=[];
chrome.storage.local.get(null,函数(结果){
var keys=Object.keys(结果);
//从chrome存储中获取所有密钥并添加到阵列项目
对于(变量i=0;i
但是,当我用文字数组替换this.props.items时,我得到了新元素。你知道我这里缺少什么吗?chrome.storage是异步的:
它与大容量读写操作是异步的,因此
比阻塞和串行本地存储API更快
这意味着getDefaultProps
在调用返回之前完成,初始状态为{items:[]}
。要解决此问题,请向中的存储器发出请求,并在数据到达时设置状态:
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>
)
}
})
React.createClass({
getDefaultProps:function(){
返回{
items:[//初始值为空
}
},
componentDidMount:function(){//该组件已第一次呈现
chrome.storage.local.get(null,函数(结果){//接收项目
var keys=Object.keys(结果);
//从chrome存储中获取所有密钥并添加到阵列项目
对于(变量i=0;i
如果我在getInitialState中定义项,并在render函数中使用This.state.items.map,这将非常有效。谢谢