代码之家  ›  专栏  ›  技术社区  ›  ahmedg94

使用对象引用在react中设置初始状态

  •  0
  • ahmedg94  · 技术社区  · 7 年前

    在尝试遵循干燥原则的同时,我开始怀疑在react项目中是否应该鼓励/阻止以下方面:

    const DEFAULT_STATE = {
      foo: foobar,
      bar: barfoo
    }
    
    class Tuna extends Component {
      constructor(props) {
        super(props)
        this.state = DEFAULT_STATE
      }
      ...
      reset = () => {
        this.setState(DEFAULT_STATE)
      }
      ...
    }
    

    或者这会更好(假设默认_状态中没有嵌套对象)

    const DEFAULT_STATE = {
      foo: foobar,
      bar: barfoo
    }
    
    class Tuna extends Component {
      constructor(props) {
        super(props)
        this.state = {...DEFAULT_STATE}
      }
      ...
      reset = () => {
        this.setState({...DEFAULT_STATE})
      }
      ...
    }
    

    或者只是简单的旧代码(重复代码)

    class Tuna extends Component {
      constructor(props) {
        super(props)
        this.state = {
          foo: foobar,
          bar: barfoo
        }
      }
      ...
      reset = () => {
        this.setState({
          foo: foobar,
          bar: barfoo
        })
      }
      ...
    }
    

    非常感谢。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Егор Ересько    7 年前

    在任何情况下,如果不更改初始对象,都不会有问题。但如果更改对象,可能会遇到以下问题,例如:

    const DEFAULT_STATE = {
      foo: foobar,
      bar: barfoo
    }
        class Tuna extends Component {
          constructor(props) {
            super(props)
            this.state = DEFAULT_STATE
          }
          ...
          reset = () => {
            this.setState(DEFAULT_STATE)
          }
          someFunc = () => {
            this.state.foo.push({field: 'lol'})
          }
    
          someFuncAfterReset = () => {
            console.log(this.state.foo) // always [{field: 'lol'}]
          }
        }
    

    除了第三个案例