如何解决子状态更改时,子不重新渲染
我在子组件中使用模型,我想通过子状态变量管理可见性,但是当我单击按钮(也在子状态上)时,子状态变量可以成功更新,但未调用子渲染功能吗? 请查看我的代码,然后让我纠正错误的地方。
//Main Parent class
export default class ChatMessageComponent extends Component {
renderItem = ({ index,item }) => {
return (
<ChatMessageView
{...this.props}
/>
)
};
}
//ChatMessageView child
export default class ChatMessageView extends PureComponent {
render() {
return (
<View style={[styles.container,isMinimize ? { width: screenWidth - scale(20) } : null]}>
<ChatNoticeView
{...this.props}
/>
</View>
)
}
}
}
//ChatNoticeView child
export default class ChatNoticeView extends Component {
constructor(props) {
super(props);
this.state = {
visibleModal: this.props.isVisible
}
}
renderModAL = () => {
return (
<Modal
visible={this.state.visibleModal}
>
<RejectReason
/>
</Modal>
)
}
render() {
return (
<View style={styles.container}>
{this.renderModAL()}
</View>
)
}
}
//Model
export default class RejectReason extends Component {
componentDidMount() {
}
render() {
return (
<View style={styles.container}>
</View>
)
}
}
解决方法
这是因为您的孩子的功能与单击按钮时不会获得更新的状态绑定在一起。需要使用getderivedstatefromprops
方法来更新状态或将可见性与道具绑定。我已经更新了您的子组件,该组件应显示模态。
export default class ChatNoticeView extends Component {
constructor(props) {
super(props);
this.state = {
visibleModal: this.props.isVisible
}
}
renderModAL = () => {
return (
<Modal
visible={this.props.isVisible}
>
<RejectReason
/>
</Modal>
)
}
您可以了解有关getDerivedStateFromProps here
的更多信息版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。