在构造函数中进行React属性分解。是个好主意吗?

时间:2019-04-16 18:39:19

标签: javascript reactjs

通常我会在render方法中对道具进行对象分解。

喜欢:

render() {
const { props1, props2, props3 } = this.props;
...other code

非常无聊,因为如果我需要在对象中定义一个方法,也许我需要在这里使用props,那么我就需要在函数内部再次破坏props。

例如:

func = () => {
  const { props1, props2, props3 } = this.props;
}

有一种方法可以一次对组件执行此操作吗?也许在构造函数中?

4 个答案:

答案 0 :(得分:0)

只进行一次销毁,我认为最好的方法是使用功能组件和挂钩,例如以下波纹管

export default function Banans(props) {

    const {
        name,
        type,
        color
    } = props

    const bananaColor = () => {
        // here you can access the props without destructuring again
        console.log(color)
    }

    return (
        <div>
            {name}
            <button onClick={() => bananaColor()}>Banana color</button>
        </div>
    )
}

答案 1 :(得分:0)

如果该组件正常运行,则可能会出现类似情况

const myComponent = (props) => { const {props1, props2} = props; return( <div> <li>{props1}</li> <li>{props2}</li> </div> )}

答案 2 :(得分:0)

是的。在构造函数中,您可以通过道具设置状态。但是,如果父母更改了道具,则需要更改状态。查看以下生命周期方法:UNSAFE_componentWillReceiveProps()

class Clock extends React.Component {
          constructor(props) {
            super(props);
            this.state = {
             props1 = props.props1,
             props2 = props.props2,
             props3 = props.props3
        };
          }

        func = () => {
          let sum = this.state.props1 + 1;
          code...
        }

          render() {
            return (
              <div>
                <h1>Hello, world!</h1>
                <h2>It is {this.state.props1}.</h2>
                <h2>It is {this.state.props2}.</h2>
                <h2>It is {this.state.props3}.</h2>
              </div>
            );
          }
        }

答案 3 :(得分:0)

在使用类组件的情况下,您只能在一次(例如在构造函数中并将其保存为类属性,但是您将面临的问题是,每当重新渲染组件时,并且说由父组件传递的props都会更新,则保存为class属性的初始解构prop值将被保存。由将过时且过时的render方法使用。因此,在这种情况下,无法更新视图。

解结构的主要优点是使语法简短并避免使用长表达式,例如不要一次又一次地重复this.props。如果你两个都想要 解构(简短语法)+更新道具(更新视图)的正确方法是每次在render方法中对其进行解构(以便您可以直接使用它们而不必另存为类成员)。

您还可以使用componentWillUpdatecomponentWillReceiveProps钩子将props保存为类属性,并每次对其进行更新,但是再次需要this才能在render方法内访问该props 。在这里将它们保存在内部状态不是一个好主意,因为您将需要再次破坏this.state以获得更简洁的语法。