React.js:无法设置State

React.js: Unable to setState

本文关键字:设置 State js React      更新时间:2023-12-22

通常在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调用失败,因此不会设置组件的状态或重新渲染组件以在页面上显示新的搜索项(假设我在渲染函数中打印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;
  }
};

我不确定我提供了足够的上下文,所以我对此道歉。不知怎的,我的setState调用抛出了framesToPop错误,尽管只调用了setState一次。正如我所说,我在render函数中使用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})的代码。不确定为什么这样做有效:(