React-native ListView“警告:无法调用setState”

问题描述 投票:0回答:1

嘿家伙可以有人请看看这个。我无法找到它来自我最近几天在这个页面上看到的地方,我无法找到它

问题是每当我点击列表中的一个名称时,导航和值的Transver of“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>
    );
  }
}

非常感谢您提前花时间和精力:)

edit 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个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.