问题
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