reactjs - 如何修复 TypeError:this.state 为空?
问题描述
我正处于 react.js 的学习阶段,我试图通过单击按钮来复制整个 div。我需要在哪里更改代码中的状态。相应的按钮也应该相应地。添加按钮以添加 div。删除按钮以删除添加的 div。
class ReplicateDiv extends React.Component {
constructor(props) {
super(props);
this.state = { array: [] };
this.manageDiv = this.manageDiv.bind(this);
}
manangeDiv(e, type) {
const { array } = this.state.array;
if (type === "add") {
array.push(array[0]);
} else if (type === "remove") {
array.splice(0, 1);
}
this.setState({
array
});
}
render() {
return (
<div>
<button type="button" onClick={e => this.manangeDiv(e, "add")}>
add
</button>
<button type="button" onClick={e => this.manangeDiv(e, "remove")}>
remove
</button>
{this.state.array.map((item, index) => {
return <div key={index}> Dynamic Div </div>;
})}
</div>
);
}
}
```
解决方案
在constructor
你需要初始化状态变量。
constructor(props) {
super(props);
this.state = {array: [] };
}
推荐阅读
- c# - 多级继承问题
- sql - 使用dbms(时间范围)在四列中将数据插入到带有年份日期和时间的表中
- java - 如何为vertx设置一个持久的计时器,如果服务器重新启动,它不会丢失?
- python - 对象没有属性'tk' - tkinter
- typescript - 如何在不使用Jquery的情况下上传带有角度进度条的excel文件?
- terraform - 如何在 Terraform 中制作反向 PTR?
- postgresql - 如何导出和导入调查数据 Odoo 10
- mongodb - 投影性能 - 性能问题
- javascript - 使用 Jest 模拟 CTRL + V 事件
- jquery - Webpack 单独跨包共享文件