“只能在componentDidMount中更新已安装或安装的组件”警告

时间:2017-12-07 07:55:19

标签: javascript reactjs

理论上,我应该能够异步获取一些数据并在componentDidMount内更新我的组件。这是我的组成部分:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class App extends Component {
  constructor () {
    super()
    this.state = {}
  }

  componentDidMount () {
    fetch('/api/sessions')
      .then(response => response.json())
      .then(data => {
        this.setState({ sessions: data.body })
      })
  }

  render () {
    return (
      <div>
        <h1>Sessions</h1>
        <ul>
          {this.state.sessions && this.state.sessions.map(session => {
            return <li key={`session-${session._id}`}>{session._id}</li>
          })}
        </ul>
      </div>
    )
  }
}

ReactDOM.render(<App />, document.querySelector('#root'))

组件呈现,并在接收数据时重新呈现。但是我收到了警告:

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

Please check the code for the App component.

我不应该假设componentDidMount暗示组件实际安装了吗?我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

要防止它您可以维护isMounted状态并在componentWillMount和componentWillUnmount上更新它。无论何时异步尝试设置状态,首先要检查组件是否仍然挂载。

componentWillMount = () => {
  this.setState({
      isMounted: true
  })
}

componentWillUnmount = () => {
  this.setState({
      isMounted: false
  })
}

componentDidMount () {
 fetch('/api/sessions')
  .then(response => response.json())
  .then(data => {
    if (this.state.isMounted) {
       this.setState({ sessions: data.body })
    }
  })
}