[英]State leaking between React sibling components
当删除其中一个兄弟组件时,我遇到了 React 在兄弟组件之间传递 state 的问题。
在我的程序中,每个组件Plant都有一个state“watered”,默认为“”,可以按一个按钮更新到当前日期。 当我删除具有非空浇水 state 的植物时,该 state 传递到下一个植物组件。
我确信通过直接监视父项中的键正在删除正确的项目。
这与 memory 泄漏有关吗? 是否有一些代码可以添加到 componentWillUnmount() 方法来解决这个问题?
谢谢!
编辑:我的工厂 class
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 组件(主要父级)中的 state 中删除植物
removeFromGarden = key => {
const garden = {...this.state.garden };
delete garden[key]
this.setState({garden })
}
如果您使用index
作为数组中组件的键,则可能会发生这种情况。 确保删除一个元素后,所有剩余元素都保留其原始键 - 如果没有,react 会将下一个元素解释为已删除的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.