这是我的根组件,它将初始状态的url详细信息数组传递给tab_list,为每个url呈现单独的tab_item。我也传递了一个删除url的函数,但是当我这样做并对状态进行更改时,状态不会受到影响。 :
import React, { Component, PropTypes } from 'react';
import { Provider } from 'react-redux';
import TabList from './tab_list.js';
export default class Root extends Component {
constructor(props, context) {
super(props, context);
this.state = {
tabs: this.props.tabs
};
};
removeURL(key) {
console.log("This is the Key " , key);
chrome.storage.local.get({urls: []}, function (result) {
var urls = result.urls;
urls = urls.filter(function(obj) {
return obj.id != key;
});
this.state = {
tabs: urls
};
chrome.storage.local.set({urls: urls}, function () {});
});
}
render() {
return (
<div>
<TabList tabs={this.state.tabs} remove_url={this.removeURL.bind(this)}/>
</div>
);
}
}
这是我的tab_list组件 -
import React, { Component } from 'react';
import TabItem from './tab_item';
export default class TabList extends Component {
render() {
return (
<ul>
{this.props.tabs.map(function(tab, i) {
return <TabItem url={tab.url} url_id={tab.id} key={i} id={i} remove_url={this.props.remove_url}/>;
}.bind(this))}
</ul>
);
}
}
这是我的tab_item组件 -
import React, { Component } from 'react';
export default class TabItem extends Component {
render() {
var self = this;
return (
<div>
<li>{this.props.url}</li> <img src="img/ic_clear_black_24dp_1x.png" onClick={() => self.onClick(this.props)}/>
</div>
);
}
onClick(props) {
this.props.remove_url(this.props.url_id);
}
}
答案 0 :(得分:2)
您需要在存储回调中调用setState
chrome.storage.local.get({urls: []}, function (result) {
var urls = result.urls;
urls = urls.filter(function(obj) {
return obj.id != key;
});
this.setState({
tabs: urls
});
chrome.storage.local.set({urls: urls}, function () {});
}.bind(this));