Componentwillreceiveprops là gì

Có vẻ như componentWillReceivePropssẽ được loại bỏ hoàn toàn trong các phiên bản sắp tới, ủng hộ một phương pháp vòng đời mới getDerivedStateFromProps: static getDerivingStateFromProps [] .

Khi kiểm tra, có vẻ như bạn hiện không thể so sánh trực tiếp giữa this.propsvà nextProps, giống như bạn có thể tham gia componentWillReceiveProps. Có cách nào để khắc phục điều này?

Ngoài ra, bây giờ nó trả về một đối tượng. Tôi có đúng không khi cho rằng giá trị trả về cơ bản là this.setState?

Dưới đây là một ví dụ tôi tìm thấy trực tuyến: Trạng thái bắt nguồn từ đạo cụ / trạng thái .

Trước

class ExampleComponent extends React.Component { state = { derivedData: computeDerivedState[this.props] }; componentWillReceiveProps[nextProps] { if [this.props.someValue !== nextProps.someValue] { this.setState[{ derivedData: computeDerivedState[nextProps] }]; } } }

Sau

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

Video liên quan

Chủ Đề