首页 > 解决方案 > 在渲染中干净地分配嵌套的 this.props const

问题描述

render()即时传递许多变量。最佳实践似乎指向在调用 a 之前做这样的事情return <div>...etc</div

const {
        products: mainProducts,
        parent,
        getProductsByOffset,
        offset,
        count,
        formOnChange,
        isGettingMissingProducts
    } = this.props

这一切都很好,但我有一个特定的对象需要获取嵌套很深的对象。而不是让对象/ s做:

        const assignProducts = this.props.parent.props.input.values

我将如何很好地提取它。我认为它可能并且在最佳实践中能够按照我的做法做到这一点products: mainProducts

标签: javascriptreactjsreduxreact-redux

解决方案


我确实认为您的const assignProducts = this.props.parent.props.input.values外观比任何替代方案都好,但是如果您想继续解构以提取该嵌套属性,则可以使用以下语法:

const {
  products: mainProducts,
  parent,     // if you only need the `assignProducts`, remove this line
  parent: { props: { input: { values: assignProducts }}},
  getProductsByOffset,
  offset,
  count,
  formOnChange,
  isGettingMissingProducts
} = this.props

请注意,您可以同时提取parent属性(如果需要)并同时提取其中的属性parent。但这看起来比您的原始代码 IMO 更难看。


推荐阅读