简体   繁体   English

什么用于反应js,道具或状态的双向绑定?

[英]What to use for two way binding in react js , props or state?

I am trying to create a form using reactjs , I am trying out twoway binding . 我正在尝试使用reactjs创建一个表单,我正在尝试使用twoway绑定。 I am not able to use props in the valueLink because it is can only take state . 我无法在valueLink中使用props,因为它只能采用状态。

Problem 1 : I am passing in properties when creating a component and in getInitial state I am setting it into state , as I cannot use props in valueLink . 问题1:我在创建组件时传入属性,并且在getInitial状态下我将其设置为状态,因为我无法在valueLink中使用props。 What is the better approach ? 什么是更好的方法?

I want to send every change in a text box to do some computation in server and get the computed values to state. 我想在文本框中发送每个更改以在服务器中执行一些计算并将计算值发送到状态。

Problem 2 : I am unable to use method componentWillReceiveProps because , I use state .I am also unable use shouldComponentUpdate as I cannot do setState. 问题2:我无法使用方法componentWillReceiveProps因为,我使用state。我也无法使用shouldComponentUpdate,因为我无法使用setState。 What can I use here ? 我可以在这里使用什么?

valueLink doesn't work on props. valueLink不适用于道具。 You might want to try React without the two-way binding helper. 您可能想要在没有双向绑定帮助程序的情况下尝试React。 The helper is really there as a convenient sugar, not as a full library feature (since React doesn't need two-way binding). 帮助器实际上是一个方便的糖,而不是一个完整的库功能(因为React不需要双向绑定)。

For problem 1: this is an antipattern , and another reason why you should try React without the binding helper first. 对于问题1:这是一个反模式 ,另一个原因是你应该首先尝试没有绑定帮助器的React。 Let a prop stay a prop (in most cases). 让支柱保持支柱(在大多数情况下)。

For problem 2: that is also something that's made harder by your decision of using the binding helper. 对于问题2:这也是你决定使用绑定帮助器时更难的事情。 As for "unable to use shouldComponentUpdate ", I'm not sure what you mean. 至于“无法使用shouldComponentUpdate ”,我不确定你的意思。

It seems that the value of your input is controlled higher in the hierarchy and passed down as prop. 似乎您的输入值在层次结构中被控制得更高,并作为prop传递下来。 Here's what you would do without add-on: http://jsfiddle.net/TcfWe/ 以下是没有附加组件的情况: http//jsfiddle.net/TcfWe/

Note that I put the doSomeComputationOnServerSide in the parent because it feels more coherent to be alongside value 's source of truth. 请注意,我将doSomeComputationOnServerSide放在父级中,因为它与value的真实来源一起感觉更加连贯。 Depending on your needs, you might put it in the child. 根据您的需要,您可以将它放在孩子身上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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