【问题标题】:Warning: setState(...) on ComponentDidMount when navigating using react-router警告:使用 react-router 导航时 ComponentDidMount 上的 setState(...)
【发布时间】:2017-01-28 12:03:41
【问题描述】:

我有一个名为 Containers 的组件,其中有一个名为 ContainerStatus 的组件列表。

当我尝试使用 react-router<Link> 导航到我的组件时,我的子组件中收到了以下警告:

警告:setState(...):只能更新已安装或正在安装的组件。”。

但如果我使用直接链接 (localhost:3000/containers) 到我的组件,则不会触发警告。

路由器:

<Route path='/' component={App}>
  <Route path='/containers' component={Containers} />
</Route>

容器

renderData () {
  return (
    <table className={'table table-hover'}>
      <thead>
        <tr>
          <Header>ID</Header>
          <Header>Name</Header>
          <Header>IMAGE</Header>
          <Header>Server</Header>
          <Header>Actions</Header>
        </tr>
      </thead>

      <tbody>
        {
          this.props.containers.map((e, index) => (
            <tr key={index}>
              <td>{e.id}</td>
              <td>{e.containerName}</td>
              <td>{e.image}</td>
              <td>{e.server.name}</td>
              <td>
                <ContainerStatus id={e.containerName} />
              </td>
            </tr>
          ))
        }
      </tbody>
    </table>
  )
}

render () {
  return (
    <div>
      <StyledLink to='container' style='btn btn-primary'>Create</StyledLink>
      {this.props.isFetching ? <Loader /> : this.renderData()}
    </div>
  )
}

容器状态

class ContainerStatus extends Component {
  constructor (props, context) {
    super(props, context)
    this.state = { container: {} }
    this.fetchContainer = this.fetchContainer.bind(this)
  }

  getRow (element) {
    return element.map((a, index) => <td key={index}>{a}</td>);
  }

  componentDidMount () {
    this.fetchContainer()
  }

  fetchContainer () {
    axios.get('api/containersApp/' + this.props.id)
      .then(response => { this.setState({ container: response.data }); })
      .catch((error) => { this.setState({ container: 'blabla' }); });
  }

  render () {
    return (
      <div>
        {/* do things */}
      </div>
    );
  }
}

【问题讨论】:

  • 我认为问题在于当您在 ContainerStatus 挂载后立即导航到其他页面时。 API 调用在 componentDidMount 中触发,一旦完成,如果您已经导航到另一个页面,当前代码会尝试在未安装的组件上使用 setState

标签: reactjs react-router


【解决方案1】:

您在 ajax 调用之间导航到不同的页面。最好在

上中止 ajax 调用

componentWillUnmount

方法。中止 ajax 调用将阻止此警告。

【讨论】:

    猜你喜欢
    • 2016-03-31
    • 2017-08-09
    • 1970-01-01
    • 2020-08-13
    • 2023-02-03
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    相关资源
    最近更新 更多