React-native ListView“警告:不能调用setState”

时间:2018-09-06 11:56:32

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

嘿,有人可以看看这个。我找不到最近几天来在此页面上查找的内容,也找不到

问题是每次我单击列表中的一个名称时,导航和将值转换为“ 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);
  }

1 个答案:

答案 0 :(得分:0)

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