How can I change the state of a React ponent from my old legacy jQuery soup code?
I have a ponent 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 ponentInstance = AComtonent({});
React.renderComponent(ponentInstance, document.getElementById(...));
// Somewhere else, in the jQuery soup. Something special happens:
ponentIntance.state.ids.push(1234);
ponentIntance.setState(ponentInstance.state);
This is an antipattern, according to this email from a Facebook
developer,
because he writes that ponentInstance
might be destroyed by React.
How can I change the state of a React ponent from my old legacy jQuery soup code?
I have a ponent 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 ponentInstance = AComtonent({});
React.renderComponent(ponentInstance, document.getElementById(...));
// Somewhere else, in the jQuery soup. Something special happens:
ponentIntance.state.ids.push(1234);
ponentIntance.setState(ponentInstance.state);
This is an antipattern, according to this email from a Facebook
developer,
because he writes that ponentInstance
might be destroyed by React.
- I think by design a state mutation is supposed to be internal, so if you want to change it from outside, you should use a props. Which means splitting your ponent in two in your case. IE: moving your state to something enpassing your jquery soup trigger and thus solving your problem. – plus- Commented Sep 25, 2014 at 9:59
- @plus Good to know that state mutation should be internal only. I didn't understand what you mean with "enpassing your jquery soup trigger" — did you mean that the state should be placed outside the ponent and I'd pass state mutators as props to the ponent? (As in kulesa's answer.) – KajMagnus Commented Sep 26, 2014 at 3:19
1 Answer
Reset to default 5I would make the ponent stateless. Store the ids
array outside of your ponent and pass it as a prop with functions that will modify the array. See example on JSFiddle: http://jsfiddle/ohvco4o2/5/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745057123a4608734.html
评论列表(0条)