从旧的外部Javascript更改React组件的状态?

从旧的外部Javascript更改React组件的状态?,javascript,jquery,reactjs,legacy,Javascript,Jquery,Reactjs,Legacy,如何从旧的旧jQuery汤中更改React组件的状态 密码 我有这样一个组件: var AComponent = React.createClass({ getInitialState: function() { return { ids: [] } }, render: function() { ... }, onButtonClick: function() { ids.splice(…); // remove the last id } })

如何从旧的旧jQuery汤中更改React组件的状态 密码

我有这样一个组件:

var AComponent = React.createClass({
  getInitialState: function() {
    return { ids: [] }
  },
  render: function() {
    ...
  },
  onButtonClick: function() {
    ids.splice(…); // remove the last id
  }
});
当旧jQuery代码中发生特殊情况时,我想 将id推送到
组件.state.ids
。我该怎么做

一个“明显”的解决方案是反模式;这是:

var componentInstance = AComtonent({});
React.renderComponent(componentInstance, document.getElementById(...));

// Somewhere else, in the jQuery soup. Something special happens:
componentIntance.state.ids.push(1234);
componentIntance.setState(componentInstance.state);
这是一个反模式,根据,
因为他写道,
componentInstance
可能会被React破坏。

我会使组件无状态。将
ids
数组存储在组件外部,并将其作为道具传递,其中包含修改数组的函数。参见JSFIDLE上的示例:

我认为通过设计,状态突变应该是内部的,所以如果您想从外部更改它,应该使用props。这意味着在您的案例中将组件一分为二。IE:将您的状态移动到包含jquery soup触发器的某个位置,从而解决了您的问题。@另外,很高兴知道状态突变只应该是内部的。我不明白你所说的“包含jquery汤触发器”是什么意思——你是说状态应该放在组件之外,我会将状态变量作为道具传递给组件吗?(就像库莱萨的回答一样。)