【问题标题】:Can't perform a React state update on an unmounted component. memory leak无法对未安装的组件执行 React 状态更新。内存泄漏
【发布时间】:2020-01-24 11:57:02
【问题描述】:

我正在使用 react-native-router-flux 并将地址传递给前一个组件。值通过,但我收到警告 Can't perform a React state update on an unmounted 要修复,请取消 componentWillUnmount 方法中的所有订阅和异步任务。


class ChangeAddress extends Component {

  constructor(props) {
    super(props);
    this.state = {
      text:''
    };
    this.handleChange = this.handleChange.bind(this);
  }

    onPressNext =() => {
       Actions.replace('Navigate', {text:this.state.text});
    }

    handleChange(text) {
      this.setState({ text: text });
    }

  render() {
       return(
        <View>
            <TextInput
                placeholder="Enter Address"         
                onChangeText={this.handleChange } 
            />
            <Button title =" Save Address" onPress={this.onPressNext}  />
        </View>
        );
  }
}
export default ChangeAddress;```

【问题讨论】:

    标签: reactjs react-native reactjs-flux react-native-router-flux


    【解决方案1】:

    试试这个示例代码:-

    查看我添加 _isMounted 的位置并在代码中遵循相同的操作

    class Page extends Component {
     _isMounted = false;
    
     state = {
       isLoading: true
     }
    
     componentDidMount() {
      this._isMounted = true;
    
      callAPI_or_DB(...).then(result => {
        if (this._isMounted) {
         this.setState({isLoading: false})
       }
      });
    }
    
    componentWillUnmount() {
    this._isMounted = false;
    }
    
    render() {
      return (
        <div>Whatever</div>
        );
      }
    }
    
    export default Page;
    

    【讨论】:

    • 我应该在这里写什么componentDidMount() { this._isMounted = true; callAPI_or_DB(...).then(result =&gt; { if (this._isMounted) { this.setState({isLoading: false}) } }); }我没有在我的代码中使用componentDidMount
    猜你喜欢
    • 2021-06-29
    • 2021-11-25
    • 1970-01-01
    • 2021-07-01
    • 2020-11-21
    • 2019-11-09
    • 2019-05-30
    • 2021-05-30
    相关资源
    最近更新 更多