简体   繁体   English

在react渲染器中调用格式化函数是一种不好的做法吗?

[英]Is it bad practice to call formatting functions in the react render?

I have a function like: 我有一个像这样的功能:

const getTermsUrl = (list) => {
  const allianzInsurances = (list || []).filter(isAllianz)
  return get(first(allianzInsurances), 'productUrl', '')
}

also have a component with a render method like: 也有一个带有render方法的组件,例如:

  ...
  render() {
    const { browser, list, selected, loading, invalidFields } = this.props

    // it`s bad practice to formating it in the render? 
    const termsAndConditionsProps = {
      browser,
      invalidFields,
      termsUrl: getTermsUrl(list), 
    }

    return (<TermsAndConditions {...termsAndConditionsProps} />)
  }
  ...

My question is: is it bad practice to format termsAndConditionsProps during render? 我的问题是:在渲染过程中格式化termsAndConditionsProps是不好的做法吗? Or is it better to keep the formatted version in the local state and format within the constructor? 还是将格式化的版本保持在构造器中的本地状态和格式更好?

It is ok to have lightweight formatting functions and call them inside of component's render method. 可以使用轻量级的格式化功能,并在组件的render方法中调用它们。 It makes sense to move such computations in constructor if your prop's don't change. 如果您的道具不变,则在构造函数中移动此类计算是有意义的。 But in the case above your component already gets re-rendered every time when the list property gets updated. 但是在上述情况下,每次list属性更新时,组件都已重新呈现。 So in this case it's ok. 因此,在这种情况下可以。

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

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