我对 React 还是有点陌生,我觉得它很棒,但目前有一件事在我脑海中,我想知道如何看待它。
例如,我正在制作一个结账组件,其中有一个减价优惠券字段。
我将事件的当前价格传递给优惠券,以便它可以计算新的:
{this.state.showCouponField ? (
<CouponForm
validateCoupon={(coupon) => this.setState({ coupon: coupon })}
initialValue={this.state.coupon ? this.state.coupon.token : ''}
initialPrice={this.state.event.final_price}
setReducedPrice={(reducedPrice) => this.setState({ reducedPrice })}
/>
) : null}
然后显示:
<p className="lead">
Total :
<span className="pull-right">
{this.state.reducedPrice ? (
<span>
<s>
{isFree ? 'Gratuit' : `${event.real_final_price * this.state.participants} €`}
</s>
{this.state.reducedPrice === 0 ? 'Gratuit' : `${this.state.reducedPrice / 100 * this.state.participants} €`}
</span>
) : (
<span>
{isFree ? 'Gratuit' : `${event.real_final_price * this.state.participants} €`}
</span>
)}
</span>
</p>
但例如,在有人使用优惠券之前,变量 reducedPrice
为空。
问题是:将 reducedPrice
设置为初始状态是否是一个好习惯
constructor(props) {
super(props);
this.state = {
event: null,
creditCards: [],
selectedCardId: null,
addCreditCard: false,
participants: 1,
coupon: null,
total: 0,
error: null,
loading: false,
bookingId: null,
user: null,
showCardOptions: false,
showModal: false,
modalUrl: null,
};
this.updatePaymentMeans = this.updatePaymentMeans.bind(this);
}
所有这些空变量对我来说似乎都是无用的,因为它们默认为空,而且不需要初始化它们——或者我还没有看到错误——因为状态是一个对象,所以它可以动态创建。
我知道我会忘记其中的一些,所以我想知道我是否会简单地不设置它们,这样如果我错过一个,它就会明显崩溃。
开放式问题 :D
最佳答案
将它们设置为 null
或 undefined
将导致相同的结果/错误,因为您很少会使用三等号来比较它的存在。
selectedCreditCardId ? something : else
但是话又说回来,同样的事情发生在 true
/false
上,与其他类型(字符串,数字,......)相反,你很少使用三重 -两者都相等。
所以它与完全相同:this.state = { isTall: false }
,而不是完全没有它
是高吗?是:否
仍然会给您相同的结果。 (此示例旨在为您提供更好的链接上下文,稍后我将向您展示)
IMO,因为这是一个自以为是的问题
将它们定义在顶部,而不是将它们分布在渲染方法中,将提供有关当前状态和下一个状态的快速概览。
做什么,只要确保保持一致。
您可能还想检查:
- https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/containers/About/About.js
- https://github.com/fbsamples/f8app/blob/master/js/login/LoginScreen.js
- https://github.com/fbsamples/f8app/blob/master/js/common/ViewPager.js
- http://reactkungfu.com/2015/09/common-react-dot-js-mistakes-unneeded-state/
关于javascript - 我应该在 React 组件中初始化一个空状态变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41503066/