我使用了一个用于从class2更新同级class1状态的函数。第一次安装class1时它将起作用,但是当我卸载class1并在第二次安装时,class1状态不起作用
当组件将要卸载但仍无法正常工作时,我尝试更改状态,也尝试将updateVisiblity设置为null,但也无法正常工作。第二次安装和更新状态后的错误是:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.%s, the componentWillUnmount method,
这是我的代码:
import React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
class1Show : false,
buttonName: "First Time Mount class1 Class",
}
}
changeBtnName = () => {
if (this.state.class1Show) {
this.setState({buttonName: "Second Time Mount class1 Class"});
} else {
this.setState({buttonName: "Unmount class1 Class"});
}
}
render() {
return (
<>
<View style={{margin:30}}>
<Button title={this.state.buttonName}
onPress={() => {
this.changeBtnName()
this.setState({class1Show: !this.state.class1Show})}
} />
</View>
<Class2 />
{ this.state.class1Show ? (
<Class1 />
) : (
<></>
)}
</>
)
}
}
export function updateVisiblity(visibleChild){
this.setState({visibleChild})
}
class Class1 extends React.Component {
constructor(props) {
super(props)
this.state = {
visibleChild : false,
}
updateVisiblity = updateVisiblity.bind(this)
}
componentDidMount() {
console.log("class1 did mount")
}
componentWillUnmount() {
console.log("class1 will unmount")
this.setState({updateVisiblity: true}) //here
this.updateVisiblity = null; //and here
}
render() {
return (
<>
{ this.state.visibleChild ? (
<View style={styles.container}>
<Text style={[styles.paragraph]}>"visibleChild" state is true</Text>
</View>
) : (
<View style={styles.container}>
<Text style={[styles.paragraph]}>"visibleChild" state is false</Text>
</View>
)}
</>
)
}
}
class Class2 extends React.Component {
constructor(props) {
super(props)
this.state = {
toggleBool: true,
}
}
componentDidMount() {
console.log("class2 did mount")
}
componentWillUnmount() {
console.log("class2 will unmount")
}
render() {
return (
<>
<View style={{margin:30}}>
<Button title="Change class1 state" color="rgb(128, 204, 117)"
onPress={() => {
this.setState({toggleBool: !this.state.toggleBool})
updateVisiblity(this.state.toggleBool)
}} />
</View>
</>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: 20,
padding: 8,
backgroundColor: "rgb(161,144,220)"
},
paragraph: {
margin: 24,
fontSize: 15,
fontWeight: 'bold',
textAlign: 'center',
},
});
您可以在here上实时查看代码
这是一个错误吗?怎么解决?