【问题标题】:Where should react-thunk func go if no componentWillReceiveProps?如果没有 componentWillReceiveProps,react-thunk func 应该去哪里?
【发布时间】:2018-03-30 03:27:53
【问题描述】:

由于 React 16.3 已经到来,我正在尝试重构我的代码以使用新的和首选的 static getDerivedStateFromProps(),但这是我目前在我的 componentWillReceiveProps 中拥有的内容

componentWillReceiveProps(nextProps) {
    if (nextProps.chatId !== this.props.chatId) 
        this.subscribeChatMessages(nextChatId)  // a redux-thunk function 
}

由于静态函数不能从this调用任何东西,我该怎么办?

我可以把redux-thunk函数移到shouldComponentUpdate,但是好像没有错?

【问题讨论】:

  • 你能分享subscribeChatMessages(..)的定义吗?
  • 标准代码,将从后端获取一些内容并在使用 redux-thunk 异步发送数据后发送数据

标签: reactjs react-redux redux-thunk


【解决方案1】:

由于subscribeChatMessages(..)是一个有副作用的redux-thunk-action函数,你应该把它放在componentDidUpdate(prevProps, prevState, snapshot)中。

componentDidUpdate(prevProps) {
    if (nextProps.chatId !== this.props.chatId) 
        this.subscribeChatMessages(nextChatId)  // a redux-thunk function 
}

【讨论】:

  • 如问题所述,静态函数无法从this 调用任何内容,因此调用将在static getDerivedStateFromProps() 中失败
  • 那么你应该使用componentDidUpdate(prevProps, prevState, snapshot)还有一个原因,正如我在最后提到的那样。我将编辑我的帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
  • 2020-06-08
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多