React应用程序中的数据流 [英] data flow in react application

查看:93
本文介绍了React应用程序中的数据流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习反应,我遇到了从组件中优雅地提取状态的问题.

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!

推荐答案

您通常将回调从父组件传递到子组件作为道具.当状态在任何子组件中更改时,它将调用该回调并传递每种用例中合适的任何数据.然后,"controller-view"(实现实际回调的根组件)会根据当前状态执行所需的任何业务逻辑,然后相应地更新其状态(导致从该组件向下重新渲染组件树).阅读有关组件通信的文档.

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.

类似这样的东西:

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

这篇关于React应用程序中的数据流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆