【问题标题】:Correctly destructuring this.props for the whole component正确解构整个组件的 this.props
【发布时间】:2016-11-01 10:36:12
【问题描述】:

我今天遇到一个问题,考虑以下组件:

export default class Input extends React.Component {
  someFunction() {
    console.log(this.props.value)
  }

  render () {
    const { type, value, required } = this.props
    return (
      <div className={cx('Input')}>
        <input type={type} value={value} required={required} />
      </div>
    )
  }
}

我已经成功解构this.props 并且可以在渲染中使用它们,但是如果我需要在它之外使用道具值,即在someFunction() 内部我不确定如果我搬出去会有什么后果@ 987654324@ 并包含在 export default class Input extends React.Component { 行之后。这仍然有效吗?

【问题讨论】:

  • 如果你这样做,this.props 将是未定义的,因为它将在项目被渲染之前执行。你为什么要这么做?
  • @JuanMendes 为了保持一致性,所以我也不需要在 render 之外编写 this.props
  • 我不明白你在做什么,试图避免重复const { type, value, required } = this.props?我想说的是坏主意,您可能需要在不同的方法中使用不同的值。如果你写了一个你想避免重复的真实例子,那么你有一个更好的问题。不清楚你为什么需要这个,看起来你过度设计了它
  • "...成功解耦this.props ..." - 你的意思是destructuring 吗?
  • @naomik 更新了,我就是这个意思

标签: javascript object reactjs ecmascript-6 react-jsx


【解决方案1】:

如果你把它移到外面,它们会是 null ,因为那时构造函数不会被调用。

将其保持在渲染或函数中是一种推荐方法,因为您的父组件可以更改状态,这将导致您的孩子重新渲染,因此您需要为每次渲染提供新的道具。

【讨论】:

    【解决方案2】:

    正确解构整个组件的 this.props

    你不能那样做。解构只能分配局部变量,因此您需要在每个函数中解构props。否则写this.props.value也没什么问题。在有助于提高可读性时使用解构,而不仅仅是因为您不想输入 this.props。

    我会这样写你的代码

    // import cx from whatever
    
    const someFunction = value=> console.log(value)
    
    export const Input = ({type, value, required}) => (
      someFunction(value),
      <div className={cx('Input')}>
        <input type={type} value={value} required={required} />
      </div>
    )
    

    【讨论】:

      【解决方案3】:

      也许考虑将其更新为功能组件。

      function someFunction(props) {
        console.log(props.value)
      }
      
      function Input(props) {
        const { type, value, required } = props;
      
        someFunction(props); // logs props.value
      
        return (
          <div className={cx('Input')}>
            <input type={type} value={value} required={required} />
          </div>
        )
      }
      
      export default Input;
      

      【讨论】:

      • 我认为 OP 希望变量 type, value, required 已经在其他函数中定义?很难掌握 OP 真正在寻找什么......
      • 啊,我明白了。我认为它们将不得不被传递。一个 redux 解决方案可以很好地处理这个问题。
      猜你喜欢
      • 2018-03-07
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      相关资源
      最近更新 更多