如何在 FlatList 的 renderItem 中调用 fetch()?

How to call fetch() inside renderItem on FlatList?

到目前为止我一直无法解决这个问题,希望这里的人能帮助我:)

情况如下:

  1. 我使用 API 从一个部门加载用户列表,其中 returns 为 JSON(有效)。

  2. 对于 JSON 文件中的每个用户,我必须获取另一个包含传感器数据的 JSON 文件(这不起作用)。

我实际上能够从 getStatus() 函数获取 JSON 数据,但它不正确。因为,当渲染 FlatList 时,数据仍然没有被获取,但是在刷新时,调用 fetchUsers(),传感器数据显示出来,但它显示相同的传感器数据用户而不是他们自己的特定传感器数据。

目前我已经让它吐出它在 Text 元素中收到的任何 JSON 以查看返回的内容...

我这里不允许上传图片,但是我在Imgur上做了一个相册,里面有应用程序的图片来帮助解释这个问题:https://imgur.com/a/5XLpR

export default class SensorData extends Component {
constructor(props) {
    super(props);
    this.stats = null;
    this.state = { 
        isLoading: true,
        error: false,
        userDataSource: [],
        refreshing: false,
        time: 30,
        navigation: props.navigation,
    };
}

componentDidMount() {
    this.fetchUsers();
}

fetchUsers(){
    return fetch('http://url-to-the-json/json/patients.json')
        .then((response) => response.json())
        .then((response) => {
            this.setState({
                isLoading: false,
                error: false,
                userDataSource: response,
                refreshing: false,
                time: 30,
            }, function () {

            });
        })
        .catch((error) => {
            this.setState({
                isLoading: false,
                error: true
            })
        });
}

getStatus(patientId) {
    fetch("http://url-to-the-json/json/status/" + patientId + ".json")
        .then((response) => response.json())
        .then((responseJson) => {
            this.stats = responseJson;
        })
        .catch((error) => {
            Alert.alert("Error");
        });
    return this.stats;
};

renderItem(item, index) {
    var x = index % 2 === 0;
    status = this.getStatus(item.patientId);
    return (
        <View style={x ? styles.rowEven : styles.rowOdd}>
            <TouchableOpacity style={styles.rowName} onPress={this.handlePress.bind(this, item)}>
                <Text style={styles.rowNameText}>{item.firstname} {item.lastname}</Text>
            </TouchableOpacity>
            <Text>{JSON.stringify(status)}</Text>
        </View>          
    )
}

render() {
    return (
        <View>
            <View style={styles.reloadTimer}>
                <Text style={styles.timerText}>Reloading in {this.state.time} seconds.</Text>
            </View>
            <View style={styles.listView}>
            <FlatList
                    data={this.state.userDataSource}
                    renderItem={({ item, index }) => this.renderItem(item, index)}
                    keyExtractor={item => item.patientId}
                    refreshing={this.state.refreshing}
                    onRefresh={this.handleRefresh}
                    ItemSeparatorComponent={this.renderSeparator}
            />
            </View>
        </View>
    );
}
}

变量 status 是有问题的。

我希望我以易于理解的方式提出问题。

用户 JSON 文件如下所示:

  {
    "patientId": "ec276ca9-f9ab-429b-b34e-23fcf448d714",
    "firstname": "Julie",
    "lastname": "Nielsen",
    "birthDate": "1930-01-01T00:00:00Z",
    "departmentId": "709f59ae-67fe-447c-bed3-7b5912703861",
    "patientNumber": null,
    "entryDate": null,
    "dischargeDate": null,
    "editedOn": null,
    "editedBy": null
  }

传感器数据 JSON 文件如下所示:

{
"status": {
      "in_bed": false,
      "in_room": true,
      "clean_diaper": true
    }
}

您需要像处理患者 JSON 一样将 getStatus 的结果存储在组件状态中。假设您所在的州有一个 "stats" 对象将患者映射到他们的统计数据,您可以执行以下操作:

getStatus(patientId) {
    fetch("http://url-to-the-json/json/status/" + patientId + ".json")
        .then((response) => response.json())
        .then((responseJson) => {
            let stats = Object.assign({}, this.state.stats);
            stats[patientId] = responseJson;
            this.setState({ stats: stats });
        })
        .catch((error) => {
            Alert.alert("Error");
        });
};

然后,在 renderItem 函数中,您可以从状态中呈现统计信息,或者在尚未加载统计信息的情况下呈现占位符文本。 此外,您不应该在渲染函数内发出网络请求,因为它们可能会被同一个组件多次调用。相反,您应该查看 FlatList API 和可见性变化的回调。

希望这对您有所帮助...