gpt4 book ai didi

javascript - react - setState(...): Can only update a mounted or mounting component

转载 作者:行者123 更新时间:2023-11-30 07:04:00 25 4
gpt4 key购买 nike

在使用 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。可以直接设置状态:

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 });
}
...

关于javascript - react - setState(...): Can only update a mounted or mounting component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42909470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com