React: can you use setState with existing state object?

后端 未结 3 446
盖世英雄少女心
盖世英雄少女心 2021-01-28 23:09

Lets say I have a React component that has a \"state\" with 10 fields:

this.state = {
    field1: 1,
    field2: 2,
    ... other fields
    something: \'a\'
};
         


        
相关标签:
3条回答
  • 2021-01-28 23:48

    To update single field you need to pass object with this field. React will merge it for you.

    this.setState({something: 'b'})
    
    0 讨论(0)
  • 2021-01-28 23:49

    NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

    use Object.assign for clone object

    const newState = Object.assign({}, this.state, {
      something: 'b'
    })
    
    this.setState(newState)
    

    Or you can merge current state:

    this.setState({
      something: 'a',
      something2: 'b', 
    })
    
    0 讨论(0)
  • 2021-01-29 00:03

    You would actually mark all the members of State as optional.

    interface State {
      field1?: number, 
      field2?: number,
    }
    

    This is not as unsafe as you might think. TypeScript added the concept of freshness to support this pattern and others.

    More

    This is covered here :

    https://basarat.gitbooks.io/typescript/content/docs/types/freshness.html#use-case--react-state

    0 讨论(0)
提交回复
热议问题