为什么不能根据propsreact设置初始状态

IT技术 reactjs ecmascript-6 state es6-class react-fiber
2021-04-26 16:32:41

我有一个 es6 react 组件,我希望状态的初始值取决于传递的 prop 的初始值,但它的值始终为 false:

AttachStateToProps 组件

<AttachStateToProps VALUE=false />

AttachStateToProps 组件:

class AttachStateToProps extends React.Component {
  state = {
    stateValue: this.props.VALUE,
  }
  render() {
    console.log('Value of Prop - ', this.props.VALUE)
    console.log('Value of State - ', this.state.stateValue)

  return null
  }
}

每次更改props VALUE 的值时,我都会得到:

`Value of Prop - false` // this changes whenever I change prop value in 
   <AttachStateToProps />

`Value of State - false` // this does not change accordingly.

认为这可能与 state/setState 异步和更旧有关,getinitialState但我不明白为什么会这样。

2个回答

从构造函数中的 props 或作为类属性初始化状态,不会在 prop 更改时更新状态。然而,react 会检测到 prop 的变化,并重新渲染组件。

例子:

要在 prop 更改时更新状态,您需要使用组件的生命周期方法

使用 React ^16.3,您可以使用静态getDerivedStateFromProps()方法从props更新状态(并对其进行初始化):

static getDerivedStateFromProps(nextProps) {    
  return {
    stateValue: nextProps.VALUE,
  }
}

对于 16.3 之前的 React 版本,您可以使用componentWillReceiveProps().

注意:componentWillReceiveProps 已弃用,但会一直工作到版本 17。

componentWillReceiveProps(nextProps, prevState) {
  this.setState({
    stateValue: nextProps.VALUE,
  })
}

在构造函数中没有 super(props) 将无法工作。

    class AttachStateToProps extends React.Component { 
constructor(props) { 
super(props); 
this.state = { stateValue: this.props.VALUE, 
} 
} 
render() { 
console.log('Value of Prop - ', this.props.VALUE) console.log('Value of State - ', this.state.stateValue) return null 
}
 }