从构造函数中的 props 或作为类属性初始化 state,不会在 prop 更改时更新 state。但是,react 确实会检测到 prop 更改,并重新渲染组件。
例子:
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>
要在 prop 更改时更新状态,您需要使用组件的生命周期方法。
使用 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>
对于 16.3 之前的 React 版本,您可以使用componentWillReceiveProps()
.
注意:componentWillReceiveProps 已被弃用,但会一直工作到版本 17。
componentWillReceiveProps(nextProps, prevState) {
this.setState({
stateValue: nextProps.VALUE,
})
}