React.js:无法setState

时间:2015-02-18 06:32:29

标签: javascript reactjs

通常在React.js中,如果我调用this.setState({data: newData})this.state.data设置为newData,则会再次呈现整个组件。

在我的代码中,我有一个搜索栏。当我按回车键时,我想将search_term设置为输入的关键字。

if (evt.keyCode == 13) {
    this.setState({search_term: keyword})
}

关键字是“dog”,evt.keyCode在此之前是13(我打印出来)。我到达了setState调用。但是,我收到了一个错误:

Uncaught TypeError: Can't add property framesToPop, object is not extensible.

这导致setState调用失败,因此,不会设置组件的状态或重新呈现组件以在页面上显示新的搜索词(假设我在render函数中打印出search_term) 。

关于如何调试的任何想法?可能会发生什么?如有需要,我可以提供更多信息,请告诉我! :)

[编辑]

这是控制台为framesToPop

带来的代码
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/

var invariant = function(condition, format, a, b, c, d, e, f) {
  if ("production" !== "development") {
    if (format === undefined) {
      throw new Error('invariant requires an error message argument');
    }
  }

if (!condition) {
    var error;
    if (format === undefined) {
      error = new Error(
        'Minified exception occurred; use the non-minified dev environment ' +
        'for the full error message and additional helpful warnings.'
      );
    } else {
      var args = [a, b, c, d, e, f];
      var argIndex = 0;
      error = new Error(
        'Invariant Violation: ' +
        format.replace(/%s/g, function() { return args[argIndex++]; })
      );
    }

    error.framesToPop = 1; // we don't care about invariant's own frame
    throw error;
  }
};

1 个答案:

答案 0 :(得分:0)

我不确定我是否提供了足够的背景,所以我为此道歉。尽管只调用setState一次,我的framesToPop调用仍以某种方式抛出了setState错误。正如我所说,我在渲染函数中使用div显示状态。

<div class='search-display'> {this.state.search_term} </div>

我正在调用一些jquery来编辑在网站上显示搜索词的html。

$(.search-display).modifyDiv()

我通过首先将search_term的状态设置为null来修复它。

this.setState({search_term: null}, function() { 
    this.updateSearchTerm(evt, keyword)
})

this.updateSearchTerm是执行this.setState({search_term, keyword})的代码。不知道为什么会这样:(