React中componentWillReceiveProps内使用lodash.get无效的问题排查
Hey there,
Let's break down your problem step by step:
First off, the main issue causing this.state.body to always be undefined is incorrect usage of Lodash's _.get, not the componentWillReceiveProps lifecycle itself (though we'll address that lifecycle's status too).
1. Fix the _.get Call
The correct signature for _.get is:
_.get(targetObject, propertyPath, [defaultValue])
Right now, you're passing nextProps.ad.submission.content as the first argument to _.get—this is invalid. If nextProps.ad or nextProps.ad.submission ever doesn't exist, this line would throw a Cannot read property 'submission' of undefined error. Even if those properties do exist, this call won't return the value you want because _.get expects the root object first, followed by a string path to the nested property.
Here's the corrected code:
const content = _.get(nextProps, 'ad.submission.content'); this.setState({ body: content });
This safely accesses the nested content property—if any level of the chain (ad, submission) is missing, _.get will return undefined (or you can pass a custom default value as the third argument, like '' or null).
2. Notes on componentWillReceiveProps
While your immediate problem isn't with this lifecycle, it's critical to note that componentWillReceiveProps is legacy and deprecated in React 16.3+. The official replacements depend on your use case:
- If you need to update state synchronously when props change, use
static getDerivedStateFromProps:
static getDerivedStateFromProps(nextProps, prevState) { // Use deep equality if ad is an object to avoid unnecessary updates if (!_.isEqual(nextProps.ad, prevState.currentAd)) { const content = _.get(nextProps, 'ad.submission.content'); return { body: content, currentAd: nextProps.ad // Track the current ad for future comparisons }; } return null; // Return null if no state update is needed }
- If you don't need synchronous state updates, handle prop changes in
componentDidUpdateinstead:
componentDidUpdate(prevProps) { if (!_.isEqual(prevProps.ad, this.props.ad)) { const content = _.get(this.props, 'ad.submission.content'); this.setState({ body: content }); } }
3. Extra Check: Prop Comparison
If ad is an object, the shallow comparison nextProps.ad !== this.props.ad might trigger updates even when the content of ad hasn't changed (since it compares references). To avoid unnecessary state updates, use Lodash's _.isEqual for deep comparison, as shown in the examples above.
内容的提问来源于stack exchange,提问作者Jenny Mok

