如何解决React同级组件之间的状态泄漏
当其中一个同胞被删除时,React在同胞组件之间的传递状态存在问题。
在我的程序中,工厂的每个组件都处于“浇水”状态,默认状态为“”,并且可以通过按下按钮将其更新为当天。当我删除具有非空浇水状态的植物时,该状态会传递到下一个植物组件。
我可以通过直接监视父项中的键来确保删除了正确的项。
这与内存泄漏有关吗?我可以添加一些代码到componentWillUnmount()方法来解决这个问题吗?
谢谢!
编辑: 我的植物课
class Plant extends React.Component {
state = {
watered : "",note: "",animate : "",modalState: false
};
noteRef = React.createRef()
water = e => {
this.toggleAnimation()
const date = new Date();
const formatDate = date.getMonth().toString().concat('/',date.getDate())
this.setState({watered : formatDate})
}
toggleAnimation = () => {
this.setState({animate : "shake"});
setTimeout(() => {
this.setState({animate : ""})
},500);
}
componentDidMount() {
this.toggleAnimation()
}
componentWillUnmount() {
}
addNote = () => {
this.setState({modalState : true})
}
hideModal = () => {
const msg = "Variety : ".concat(this.noteRef.current.value)
this.setState({note:msg})
this.setState({modalState : false })
}
render() {
return (
<div>
<Modal show={this.state.modalState}>
<Modal.Header>Enter a variety for your plant!</Modal.Header>
<Modal.Body>
<input type="text" ref={this.noteRef} placeholder="Variety"/>
</Modal.Body>
<Modal.Footer>
<button onClick={this.hideModal}>Save</button>
</Modal.Footer>
</Modal>
<Card className={"plant-card".concat(this.state.animate)} >
<Card.Body className="card-body">
<Card.Title className="plant-card-title">
<span className="plant-card-title">{this.props.name}</span>
</Card.Title>
</Card.Body>
<Card.Text>
{this.state.note}
{this.state.watered}
<Container className="icon-div">
<img src={"images/watering-can.png"}
className="small-icon"
alt="can"
onClick={this.water}/>
<img src={"images/shovel.png"}
className="icon"
alt="shovel"
onClick={() => this.props.removeFromGarden(this.props.index)}/>
<img src={"images/grain-bag.png"}
className="icon"
alt="bag"
onClick={() => this.props.addHarvests(this.props.name,1)}/>
<img src={"images/wheelbarrow.png"}
className="small-icon"
alt="bag"
onClick={this.addNote}/>
</Container>
</Card.Text>
</Card>
</div>
) }
导出默认工厂;
从我的App组件(主要父对象)的状态中删除植物
removeFromGarden = key => {
const garden = {...this.state.garden };
delete garden[key]
this.setState({garden })
}
解决方法
如果您使用index
作为数组中组件的键,则可能会发生这种情况。确保删除一个元素后,所有其余元素保留其原始键-如果不保留,则react将把下一个元素解释为已删除的键。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。