当事件被触发时,我收到一条警告信息。更新组件的最佳方法是什么。请帮助。
警告:只能更新已安装或安装的组件。这通常 表示您调用了
setState
,replaceState
或forceUpdate
未安装的组件。这是一个无操作。
import Table from "./Table";
import Tree1 from "./Tree1";
class ComponentView extends Component {
constructor(props) {
super(props);
this.onButtonClick = this.onButtonClick.bind(this);
this.state = {
viewState: <Table />
};
}
onButtonClick(event) {
event.preventDefault()
const btnValue = event.target.value;
switch (btnValue) {
case 'Table':
this.setState({ viewState: <Table /> });
break;
case 'Tree1':
this.setState({ viewState: <Tree1 /> });
break;
default:
break;
}
}
render() {
return (
<div className="animated fadeIn">
<Row>
<Col xs="12" sm="12" lg="12">
<Card>
<CardHeader>
<Button onClick={this.onButtonClick} color="primary" size="sm" value="Table" >Table</Button>
<Button onClick={this.onButtonClick} color="secondary" size="sm" value="Tree1">Tree1</Button>
</CardHeader>
<CardBody className="pb-0" style={{ height: '500px' }}>
{this.state.viewState}
</CardBody>
</Card>
</Col>
</Row>
</div>
)
}
}
答案 0 :(得分:0)
您可能需要提炼出您的问题 - 您的代码会在没有警告的情况下运行。
window.onload = () => {
console.clear();
const Row = p => <div>{p.children}</div>
const Col = p => <div>{p.children}</div>
const Card = p => <div>{p.children}</div>
const CardHeader = p => <div>{p.children}</div>
const CardBody = p => <div>{p.children}</div>
const Button = p => <button {...p} />
const Table = () => <span>Table</span>;
const Tree1 = () => <span>Tree</span>;
class ComponentView extends React.Component {
constructor(props) {
super(props);
this.onButtonClick = this.onButtonClick.bind(this);
this.state = {
viewState: <Table />
};
}
onButtonClick(event) {
event.preventDefault()
const btnValue = event.target.value;
switch (btnValue) {
case 'Table':
this.setState({ viewState: <Table /> });
break;
case 'Tree1':
this.setState({ viewState: <Tree1 /> });
break;
default:
break;
}
}
render() {
return (
<div className="animated fadeIn">
<Row>
<Col xs="12" sm="12" lg="12">
<Card>
<CardHeader>
<Button onClick={this.onButtonClick} color="primary" size="sm" value="Table" >Table</Button>
<Button onClick={this.onButtonClick} color="secondary" size="sm" value="Tree1">Tree1</Button>
</CardHeader>
<CardBody className="pb-0" style={{ height: '500px' }}>
{this.state.viewState}
</CardBody>
</Card>
</Col>
</Row>
</div>
)
}
}
const d = document.createElement('div')
document.body.appendChild(d)
ReactDOM.render(<ComponentView />, d)
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js"></script>
&#13;