【问题标题】:React props not loaded in componentDidUpdate未在 componentDidUpdate 中加载 React 道具
【发布时间】:2015-08-26 11:12:12
【问题描述】:

在反应中,如果 this.props 已加载,我该怎么办?我尝试使用 componentDidUpdate 来检查 @props 是否与 prevProps 不同,但我发现它们总是相同的:-/

我想在@props.account.subbableProperties 不为空时调用下面的函数。

uiActions.curliesPropertyReplacement
  element: @textarea
  words: @props.account.subbableProperties
  _this: @
  replaceProperty: true
  selectOnTop: true
  maxCount: 3
  callback: (e, value, strategy) =>
    @setState text:@textarea.text()

当我将上述函数放入componentDidMount时,@props.account.subbableProperties 是空白的(尚未加载)所以我不能放在那里。

我尝试使用 componentDidUpdate,但由于某种原因,此警报从未触发!

componentDidUpdate (prevProps, prevState) ->
 if !(_.isEqual(prevProps.account.subbableProperties, @props.account.subbableProperties))
     alert("they do differ!")

我也在componentWillReceiveProps中尝试过:

  componentWillReceiveProps: (newProps) ->
    console.log "newProps", newProps.account.subbableProperties
    console.log "newProps", newProps.account.subbableProperties.length
    console.log "props", @props.account.subbableProperties
    console.log "props", @props.account.subbableProperties.length

    if !(_.isEqual(newProps.account.subbableProperties, @props.account.subbableProperties))
      alert("it happens in willReceiveProps!")

似乎 newProps 和 @props 同时更新: 我做错了什么?

【问题讨论】:

  • 触发componentWillReceivePropscomponentWillUpdate 并不能保证nextProps 与当前的道具不同。如果它们相同,那绝对没问题。
  • 你应该使用this.state而不是this.props吗?也许我误解了这个问题,但 React 指南建议将道具视为不可变的,而是建议您应该更改状态。

标签: javascript reactjs


【解决方案1】:

componentDidUpdate 在你的组件发生变化后触发,这个变化来自 DOM,所以总是在组件重新渲染自己时触发。

我不太明白你在说什么,因为我不知道this.props 会在哪里,但是你试过componentWillReceiveProps() 吗?这似乎更合适,因为您正在等待更新某些道具而不是整个组件。

编辑:好的,我刚刚留言,看到您更新了您的帖子。 所以你已经尝试componentWillReceiveProps 并提供更多信息。如果您正在等待更改某些道具或状态,您可能应该尝试componentWillUpdate 看看它们是否不同。如果您有消息,我稍后会回来查看:^)。

【讨论】:

  • 尝试过 componentWillUpdate 并看到与 componentWillReceiveProps 类似的行为。反应松弛通道中的某人建议@props 和 nextProps(或 prevProps)可能会在没有触发的情况下立即更改,因为“我猜(我可能错了)comonentWillReceiveProps 在浅道具上的触发器发生了变化,而你正在改变更深的树而不是浅”
猜你喜欢
  • 2020-09-15
  • 2021-07-09
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 2017-04-19
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
相关资源
最近更新 更多