data flow in react application

本秂侑毒 提交于 2019-12-06 16:03:00

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/

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