React Native接收新道具,componentWillReceiveProps

React Native receving new props, componentWillReceiveProps

本文关键字:componentWillReceiveProps 新道具 Native React      更新时间:2023-09-26

我正在努力更新我的组件。我知道我不应该在状态中设置道具。然而,我必须这样做才能使我的组件正确更新:

componentWillReceiveProps(nextProps) {
    this.setState({
      doctor: nextProps.data.name,
      address: nextProps.data.address 
    })
}

有更好的方法吗?如果我这样做是最好的方法->

componentWillReceiveProps(nextProps) {
        this.props.data.name = nextProps.data.name;
        this.props.data.name = nextProps.data.address;
     })
 }

我试图使用shouldComponentUpdate:

shouldComponentUpdate: function(nextProps, nextState) {
  return nextProps.id !== this.props.id;
}

但我的工作不太好。c

在您的评论中,您提到:

当我回到列表时查看我不喜欢的项目仍然在那里另一个项目消失了

这看起来是一个完全不同领域的问题。我的猜测是,您在列表中使用了错误的key。可能是一个索引。键应该始终是您显示的项目的唯一键,而索引不是(例如,第一个项目始终是索引0,当您重新排列列表或删除第一个项目时,另一个项目将具有索引0,此时react无法正常工作。)。

关于"正确更新组件":

  • 如果传入新道具,则会自动使用新道具重新渲染。您不需要为此在componentWillReceiveProps中执行任何操作
  • componentWillReceiveProps用于在比较旧道具和新道具的基础上更新状态。(例如,如果你想显示道具中的点赞数是上升还是下降)
  • shouldComponentUpdate是可选的。主要目的是在不改变组件工作方式的情况下提高性能:尽早告知react组件没有变化。我建议不要包括shouldComponentUpdate,只要您的组件还不能按预期工作

这里有一个粗略的猜测。据我所知,您在正确执行shouldComponentUpdate时会遇到问题。我相信您尝试比较nextProps.data对象,结果总是不相等,即使其中的数据相等。原因是data对象的对象引用不同。为了克服这个问题,您应该进行深入的比较,类似于lodash的_.isEqual

正如评论中提到的,在componentWillReceiveProps中更新nextOps是一个可怕的想法。

相关文章:
  • 没有找到相关文章