Change state of React component from old external Javascript?

让人想犯罪 __ 提交于 2020-01-01 03:25:27

问题


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

I have a component like this:

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

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

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


回答1:


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/



来源:https://stackoverflow.com/questions/26026097/change-state-of-react-component-from-old-external-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!