You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 componentDidUpdate instead:
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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:54:28