从旧的外部Javascript更改React组件的状态? [英] Change state of React component from old external Javascript?

查看:100
本文介绍了从旧的外部Javascript更改React组件的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从旧的遗留jQuery汤
代码中更改React组件的状态?

How can I change the state of a React component from my old legacy jQuery soup code?

我有一个这样的组件:

var AComponent = React.createClass({
  getInitialState: function() {
    return { ids: [] }
  },
  render: function() {
    ...
  },
  onButtonClick: function() {
    ids.splice(…); // remove the last id
  }
});

当旧的jQuery汤代码发生特殊情况时,我想要
推送id为 AComponent.state.ids 。我怎么能这样做?

When something special happens in the old jQuery soup code, I'd like to push an id to AComponent.state.ids. How can I do that?

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

One "obvious" solution is an anti-pattern; here it is:

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

这是一个反模式,根据来自Facebook
开发者的这封电子邮件

因为他写了 componentInstance 可能会被React销毁。

This is an antipattern, according to this email from a Facebook developer, because he writes that componentInstance might be destroyed by React.

推荐答案

我会让组件无状态。将 ids 数组存储在组件外部,并将其作为prop来传递,其中包含将修改数组的函数。请参阅JSFiddle上的示例: http://jsfiddle.net/ohvco4o2/5/

I would make the component stateless. Store the ids array outside of your component and pass it as a prop with functions that will modify the array. See example on JSFiddle: http://jsfiddle.net/ohvco4o2/5/

这篇关于从旧的外部Javascript更改React组件的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆