React - setState(...):只能更新已安装或安装的组件

时间:2017-03-20 16:53:55

标签: javascript reactjs ecmascript-6 components state

使用react-router在辅助组件内部时出现setState错误。任何人都可以在我的代码中看到任何问题吗?

import React, { Component } from 'react';
import { Row, Col } from 'react-bootstrap';
import { Card, CardTitle, CardText } from 'material-ui/Card';
import './App.css';

class Dashboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      info: []
    };
    this.setInfo = this.setInfo.bind(this);

    this.setInfo();
  }

  setInfo = () => {
    var info = [
      {
        id: 0,
        title: 'Server Space',
        subtitle: '',
        textContent: ''
      },
      {
        id: 1,
        title: 'Pi Space',
        subtitle: '',
        textContent: ''
      }
    ];
    this.setState({ info: info });
  }

  render() {
    return (
      <div>
        <h2>Info</h2>
        <Row>
          {this.state.info.map((inf) => {
            return (
              <Col xs={12} md={4} key={inf.id}>
                <Card className="card">
                  <CardTitle title={inf.title} subtitle={inf.subtitle} />
                  <CardText>{inf.textContent}</CardText>
                </Card>
              </Col>
            )
          })}
        </Row>
      </div>
    )
  }
}

export default Dashboard;

这导致:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Dashboard component.

有问题的行是this.setState({ info: info });

2 个答案:

答案 0 :(得分:7)

您不应该在构造函数中调用this.setState。 您可以直接设置状态:

var info = [
  {
    id: 0,
    title: 'Server Space',
    subtitle: '',
    textContent: ''
  },
  {
    id: 1,
    title: 'Pi Space',
    subtitle: '',
    textContent: ''
  }
];

class Dashboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      info: info
    };
    this.setInfo = this.setInfo.bind(this);
  }

  setInfo = () => {
    this.setState({ info: info });
  }
  ...

答案 1 :(得分:4)

在安装组件之前调用组件constructor,因此您无法在其中调用setStatesetState只能在已安装的组件上调用)。构造函数是初始化状态的正确位置,但您应该通过直接设置状态来完成:

constructor(props) {
  super(props);
  var info = [...];
  this.state= {
    info: info
  };
} 

请注意,在constructor之外,您永远不应该直接设置状态 - constructor是唯一可以执行此操作的例外情况。