简体   繁体   中英

data flow in react application

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!

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM