gpt4 book ai didi

javascript - React 组件在其 props 方面必须表现得像纯函数吗?

转载 作者:数据小太阳 更新时间:2023-10-29 05:28:46 24 4
gpt4 key购买 nike

我正在浏览 React 文档并阅读这一行(粗体显示他们的):

All React components must act like pure functions with respect to their props.

这是避免意外行为的严格要求还是设计原则?

Facebook 提供的“不纯”函数示例是修改其输入的函数。但是 React 组件似乎可以修改它作为输入接收的 Prop (我已经从他们自己的示例中复制了下面的示例)。

Code Pen: Impure Component w/ Respect to Props?

JSX 代码:

var Withdraw = React.createClass({
render() {
this.props.account.balance -= this.props.amount;
return (
<div>Balance: ${this.props.account.balance} </div>
)
}
})

var CounterContainer = React.createClass({
render() {
var account = { balance: 10 }
return (
<div>
<Withdraw account={account} amount={2} />
<Withdraw account={account} amount={2} />
</div>
)
}
})

React.render(<CounterContainer />, document.getElementById('app'))

另外:我知道上面的可以写成一个无状态的功能组件,并且那个状态不应该存储在this.state之外。

最佳答案

就像facebook说的,如果你需要它改变。使用状态。

函数必须是纯粹的,意思是

  1. 给定相同的参数值,该函数总是计算相同的结果值。函数结果值不能依赖于任何隐藏信息或在程序执行过程中或程序的不同执行之间可能发生变化的状态,也不能依赖于来自 I/O 设备的任何外部输入。

  2. 结果的评估不会导致任何语义上可观察到的副作用或输出,例如可变对象的突变或输出到 I/O 设备。

换句话说,一个纯函数

  • 给定相同的输入,将始终返回相同的输出。
  • 没有副作用.不依赖外部状态。

React is pretty flexible but it has a single strict rule:

All React components must act like pure functions with respect to their props.

Of course, application UIs are dynamic and change over time. In the next section, we will introduce a new concept of "state". State allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule.

你的 Facebook Link

这是一个不错的 article

更多关于 pure functions

关于javascript - React 组件在其 props 方面必须表现得像纯函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41133473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com