【发布时间】: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 同时更新: 我做错了什么?
【问题讨论】:
-
触发
componentWillReceiveProps或componentWillUpdate并不能保证nextProps与当前的道具不同。如果它们相同,那绝对没问题。 -
你应该使用
this.state而不是this.props吗?也许我误解了这个问题,但 React 指南建议将道具视为不可变的,而是建议您应该更改状态。
标签: javascript reactjs