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

Tim*_*mmo 1 javascript components state ecmascript-6 reactjs

我在setState使用react-router的辅助组件内部时收到错误.谁能在我的代码中看到任何问题?

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;
Run Code Online (Sandbox Code Playgroud)

这导致:

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.
Run Code Online (Sandbox Code Playgroud)

这条线是 this.setState({ info: info });

Mat*_*our 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 });
  }
  ...
Run Code Online (Sandbox Code Playgroud)