如何从旧的遗留 jQuery soup 更改 React 组件的状态 代码?
我有这样一个组件:
var AComponent = React.createClass({
getInitialState: function() {
return { ids: [] }
},
render: function() {
...
},
onButtonClick: function() {
ids.splice(…); // remove the last id
}
});
当旧的 jQuery soup 代码中发生一些特别的事情时,我想
将 id 推送到 AComponent.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);
根据this email from a Facebook
developer,这是一个反模式,
因为他写道 componentInstance
可能会被 React 破坏。
最佳答案
我会让组件无状态。将 ids
数组存储在您的组件之外,并将其作为具有修改数组的函数的 prop 传递。请参阅 JSFiddle 上的示例:http://jsfiddle.net/ohvco4o2/5/
关于javascript - 从旧的外部 Javascript 更改 React 组件的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26026097/