ดูเหมือนว่าcomponentWillReceivePropsเป็นไปได้ที่จะค่อย ๆ ออกมาในรุ่นมาในความโปรดปรานของวิธีการที่วงจรชีวิตใหม่getDerivedStateFromProps: getDerivedStateFromProps คงที่ ()
เมื่อตรวจสอบก็ดูเหมือนว่าคุณอยู่ในขณะนี้ไม่สามารถที่จะทำให้การเปรียบเทียบโดยตรงระหว่างthis.propsและเช่นเดียวกับที่คุณสามารถในnextProps componentWillReceivePropsมีวิธีแก้ไขไหม?
นอกจากนี้มันจะส่งคืนวัตถุ ฉันถูกต้องหรือไม่ที่จะสมมติว่าค่าส่งคืนเป็นหลักthis.setStateหรือไม่
ด้านล่างเป็นตัวอย่างที่ผมพบออนไลน์: รัฐที่ได้มาจากการประกอบฉาก / รัฐ
ก่อน
class ExampleComponent extends React.Component {
state = {
derivedData: computeDerivedState(this.props)
};
componentWillReceiveProps(nextProps) {
if (this.props.someValue !== nextProps.someValue) {
this.setState({
derivedData: computeDerivedState(nextProps)
});
}
}
}
หลังจาก
class ExampleComponent extends React.Component {
// Initialize state in constructor,
// Or with a property initializer.
state = {};
static getDerivedStateFromProps(nextProps, prevState) {
if (prevState.someMirroredValue !== nextProps.someValue) {
return {
derivedData: computeDerivedState(nextProps),
someMirroredValue: nextProps.someValue
};
}
// Return null to indicate no change to state.
return null;
}
}
componentWillReceiveProps