Почему не могу отреагировать установить начальное состояние на основе реквизита - PullRequest
0 голосов
/ 18 мая 2018

У меня есть компонент реакции es6, который я хочу, чтобы начальное значение состояния зависело от значения переданного пропа, но его значение всегда ложно:

Компонент 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
  }
}

Каждый раз, когда изменяется значение VALUE, я получаю:

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

и

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

I figure это может быть как-то связано с асинхронностью состояния / setState и старше getinitialState, но я не понимаю, почему это так.

Ответы [ 2 ]

0 голосов
/ 07 июля 2018

Не будет работать без супер (реквизита) в конструкторе.

    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 
}
 }
0 голосов
/ 18 мая 2018

Инициализация состояния из подпорок в конструкторе или в качестве свойства класса не будет обновлять состояние при изменении реквизита.Тем не менее, реагирование обнаруживает изменение реквизита и повторно отображает компонент.

Пример:

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
  }
}

const renderWithVal = (val) => ReactDOM.render(
  <AttachStateToProps VALUE={val} />,
  demo
);

renderWithVal(5);
renderWithVal(15);
renderWithVal(115);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="demo"></div>

Для обновления состояния при изменении реквизита необходимо использовать метод жизненного цикла компонента .

с React^ 16.3 Вы можете использовать статический метод getDerivedStateFromProps() для обновления состояния из реквизита (а также для его инициализации):

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

class AttachStateToProps extends React.Component {
  state = {};

  static getDerivedStateFromProps(nextProps) {    
    return {
      stateValue: nextProps.VALUE,
    }
  }
      
  render() {
    console.log('Value of Prop - ', this.props.VALUE)
    console.log('Value of State - ', this.state.stateValue)

  return null
  }
}

const renderWithVal = (val) => ReactDOM.render(
  <AttachStateToProps VALUE={val} />,
  demo
);

renderWithVal(5);
renderWithVal(15);
renderWithVal(115);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="demo"></div>

В версиях React до 16.3 вы можете использовать componentWillReceiveProps().

Примечание: componentWillReceiveProps устарела,но будет работать до версии 17.

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