【问题标题】:React-native ListView "Warning: Can't call setState"React-native ListView“警告:无法调用setState”
【发布时间】:2019-02-11 16:30:05
【问题描述】:

大家好,有人可以看看这个。最近几天我一直在这个页面上查找它的来源,但我找不到它

问题是每次当我单击列表中的一个名称时,导航和将值转换为“global.dialed”都可以正常工作,但我总是收到此警告,并且应用程序似乎执行了一点之后变慢(但较慢的性能非常轻微,可能只是一种错觉)

完全错误:

Warning: Can't call setState (or forceUpdate) 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 the componentWillUnmount 
method. 

stacktrace 指向第 25 行

RecentCalls.js:

import React, { Component } from "react";
import { Text, View, ListView, TouchableHighlight } from "react-native";
import styles from "./../Styles/styles";
import global from "./../Components/global";

export default class RecentCalls extends Component {
  constructor() {
    super();
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    this.state = {
      userDataSource: ds
    };
  }

  componentDidMount() {
    this.fetchUsers();
  }

  fetchUsers() {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then(response => {
        this.setState({
          userDataSource: this.state.userDataSource.cloneWithRows(response)
        });
      });
  }

  onPress(user) {
    this.props.navigation.navigate("Home3", {});
    global.dialed = user.phone;
  }

  renderRow(user, sectionId, rowId, highlightRow) {
    return (
      <TouchableHighlight
        onPress={() => {
          this.onPress(user);
        }}
      >
        <View style={[styles.row]}>
          <Text style={[styles.rowText]}>
            {user.name}: {user.phone}
          </Text>
        </View>
      </TouchableHighlight>
    );
  }

  render() {
    return (
      <View style={styles.padding2}>
        <ListView
          dataSource={this.state.userDataSource}
          renderRow={this.renderRow.bind(this)}
        />
      </View>
    );
  }
}

非常感谢您提前付出的时间和精力:)

编辑 1

根据milkersarac我试过(见下文)但没有任何区别

将构造函数编辑为:

  constructor() {
    super();
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    this.state = {
      userDataSource: ds
    };
    this.fetchUsers = this.fetchUsers.bind(this);
  }

【问题讨论】:

    标签: android listview react-native warnings react-navigation


    【解决方案1】:

    您需要在组件的构造函数中.bind(this) 更新组件状态的函数。即尝试将 this.fetchUsers = this.fetchUsers.bind(this) 添加为 ctor 的最后一行。

    【讨论】:

    • 试过(见 Question#Edit1),但遗憾的是它没有任何区别
    猜你喜欢
    • 2019-02-11
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 2016-02-22
    • 2019-08-23
    • 2018-02-07
    • 2019-03-10
    相关资源
    最近更新 更多