我对React还是有点陌生​​,我觉得它很棒,但是我现在想着一件事,我想知道该怎么想。

例如,我正在制作一个结帐组件,其中有一个减价优惠券字段。

我将 Activity 的当前价格传递给优惠券,以便可以计算出新的价格:

{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>
        &nbsp;
        {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为null,直到有人使用优惠券为止。

问题是:将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);
}

所有这些空变量在我看来都是无用的,因为默认情况下它们为空,并且不需要初始化-或我还没有看到bug-因为状态是一个对象,因此可以动态创建它。

我知道我会忘记其中的一些,所以我想知道我是否不会简单地设置它们,以便在我错过其中一个的情况下会明显损坏。

公开问题:D

最佳答案

将它们作为nullundefined会将您引向相同的结果/错误,因为您很少使用三重相等来比较其存在。

selectedCreditCardId ? something : else

但是话又说回来,true/false也发生了同样的事情,与其他类型(字符串,数字等)相反,您很少使用三等号。

因此,它与this.state = { isTall: false }完全相同,而不是根本没有它
isTall ? yes : no
仍然会给您相同的结果。 (此示例为您提供了更好的上下文,我将在稍后向您展示这些链接)

IMO,因为这是一个自以为是的问题
将它们定义在顶部,与将它们分布在render方法上相反,将快速概述该状态以及下一个状态。

做什么,只要确保保持一致即可。

您可能还需要检查:
  • 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/
  • 09-17 13:23
    查看更多