问题
I am currently learning react and I have run into the problem of elegently extracting states from my components.
basically I have a few components which contains forms and other inputs from which I need the data in my business logic, the data I need is coupled with the state of the component. From what I understand the data should have unidirectional flow but I can't think of how I can make my data flow back towards my business logic. I could just make some interface functions which call the respective, but I feel this would violate the unidirectional flow.
anyhelp with some examples would be greatly appreciated!
回答1:
You typically pass down callbacks from parent components to child components as props. When the state changes in any of the child components, it invokes that callback and passes whatever data is appropriate in each use case. Your "controller-view" (the root component that implements the actual callback) then does whatever business logic you need based on the current state and then updates its state accordingly (causing a re-render of the component tree from that component down). Read the docs about component communication.
Something like this:
var Child = React.createClass({
onTextChange: function() {
var val = 13; // somehow calculate new value
this.props.onTextChange(val);
},
render: function() {
return <input type="text" value={this.props.val} onChange={this.onTextChange} />
}
});
var Parent = React.createClass({
onTextChange: function(val) {
var newVal = someBusinessLogic(val);
this.setState({val: newVal});
},
render: function() {
return <Child onTextChange={this.onTextChange} val={this.state.val} />
}
});
回答2:
The best way to work with data flow in React is to use the Flux pattern. You need some time to understand how it works, but it will make your life much easier as your project grows. Look at some Flux tutorial, for example this one (using the Alt flux implementation): https://reactjsnews.com/getting-started-with-flux/
来源:https://stackoverflow.com/questions/31566872/data-flow-in-react-application