当兄弟组件之一被删除时,我在兄弟组件之间传递状态时遇到问题。
在我的程序中,每个组件Plant都有一个状态“watered”,默认为“”,可以通过按一个按钮更新到当前日期。当我删除具有非空浇水状态的植物时,该状态将传递给下一个植物组件。
我确信通过直接监视父项中的键正在删除正确的项目。
这与内存泄漏有关吗?是否有一些代码可以添加到 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 })
}