Can I update a component's props in React.js?

后端 未结 6 1045
萌比男神i
萌比男神i 2020-11-27 10:15

After starting to work with React.js, it seems like props are intended to be static (passed in from the parent component), while state changes base

6条回答
  •  清酒与你
    2020-11-27 11:17

    A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.

    For instance, a Dashboard has a speed field in its state, and passes it to a Gauge child thats displays this speed. Its render method is just return . When the Dashboard calls this.setState({speed: this.state.speed + 1}), the Gauge is re-rendered with the new value for speed.

    Just before this happens, Gauge's componentWillReceiveProps is called, so that the Gauge has a chance to compare the new value to the old one.

提交回复
热议问题