[英]React - setState(…): Can only update a mounted or mounting component
我在使用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 });
您this.setState
在构造函数中调用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 });
}
...
组件constructor
元件安装之前,所以你不能打电话叫setState
在它( setState
只能在安装组件调用)。 构造函数是初始化状态的正确位置,但您应该通过直接设置状态来做到这一点:
constructor(props) {
super(props);
var info = [...];
this.state= {
info: info
};
}
请注意,外部constructor
永远不要直接设置状态- constructor
是唯一可以设置状态的例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.