Why isn't the state of Root component changing? [duplicate]

为君一笑 提交于 2019-12-12 04:24:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!