【问题标题】:Warning: Can't perform a React state update on an unmounted component (multiple components)警告:无法对未安装的组件(多个组件)执行 React 状态更新
【发布时间】:2019-11-18 11:59:55
【问题描述】:

反应原生

我正在使用导航在与此相同的组件之间移动,但 ID 不同。有些有效,有些无效,React Native 会向我显示此警告。

警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消“componentWillUnmount 方法”中的所有订阅和异步任务。

我的组件的代码:

class MotosbicisScreen extends Component {
  static navigationOptions = {
    title: 'Motos y bicis',
  };
  constructor(props) {
    super(props);

    this.state = {
      data: [],
    };
  }

  componentDidMount() {
    this.getData()
}

getData = async () => {
    const url = 'https://url';
    fetch(url).then((response) => response.json())
    .then((responseJson) =>{
        this.setState({
            data:responseJson
        })
    })
}

  renderRow = ({item}) => {
    if (item.rubroClasificado == 9) {
    if(item.imageJob == null) {
    return(          
      <Card>
      <CardItem>
      <Body>
          <Text>
            {item.Texto} 
            </Text>
            </Body>
            </CardItem>
          </Card>)
    } else {
        img = 'http://url/' +  item.imagepath;
        return(         
            <View style={styles.item}>
            <Image
            source={{ uri: img}}
            width={Dimensions.get('window').width}
            />
            </View>            
            )
    }
  }
} 

  render() {

    return (
      <View style={styles.container}>
          <FlatList style={styles.container}
        data={this.state.data}
        renderItem={this.renderRow}
        keyExtractor={(item, index) => index.toString()} 

        />
    </View>
    );

}
}

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    这是由于组件在卸载组件时调用setState(您已导航离开页面)。

    过去的解决方案是在调用 setState 之前跟踪组件是否已挂载,但这是不好的做法。

    以下文章涵盖了您的问题、旧的不良做法以及一种可能的解决方案。 (https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html)

    【讨论】:

      猜你喜欢
      • 2021-02-24
      • 2021-03-27
      • 2019-09-11
      • 2021-08-07
      • 2020-06-14
      • 1970-01-01
      • 2021-12-03
      • 2021-11-09
      相关资源
      最近更新 更多