问题
This is my Root Component, it passes an array of url details in initial state to tab_list which renders individual tab_item for each url. I am also passing a function to delete the url , but when I do that and make changes to state , the state is not affected by it. :
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>
);
}
}
This is my tab_list component -
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>
);
}
}
And this is my tab_item component -
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);
}
}
回答1:
You need to call setState in your storage callback
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));
来源:https://stackoverflow.com/questions/39188002/why-isnt-the-state-of-root-component-changing