【问题标题】:Why isn't the state of Root component changing? [duplicate]为什么 Root 组件的状态没有改变? [复制]
【发布时间】:2017-01-04 09:46:58
【问题描述】:

这是我的根组件,它将初始状态下的 url 详细信息数组传递给 tab_list,它为每个 url 呈现单独的 tab_item。我还传递了一个删除 url 的函数,但是当我这样做并对 state 进行更改时,状态不受它的影响。 :

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

}

【问题讨论】:

  • 你的状态没有更新或者子组件没有得到改变?
  • 好吧,我的 UI 中的更改不受影响。一切正常,当我单击特定网址的交叉图像时,它会在我的 chrome 存储中被删除,但不会从我的 UI 中删除。
  • 您可以在 Tablist 中使用 componentWillReceiveProps(nextPorps) 检查 Tablist 中是否存在更改状态。

标签: javascript reactjs state


【解决方案1】:

您需要在存储回调中调用 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));

【讨论】:

  • 还是不行。它给出了错误 this.setState is not a function
  • 更新了,忘记绑定了(假设你用的是es6)
  • 非常感谢。它奏效了。
  • 不用担心。祝你好运
猜你喜欢
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 2018-06-03
  • 2020-08-21
  • 1970-01-01
相关资源
最近更新 更多