【问题标题】:How to call fetch() inside renderItem on FlatList?如何在 FlatList 上的 renderItem 内调用 fetch()?
【发布时间】:2017-10-19 16:31:12
【问题描述】:

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

情况如下:

  1. 我使用一个 API 加载一个部门的用户列表,该 API 将其返回为 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
    }
}

【问题讨论】:

  • 你试过在 renderItem 函数中使用 async-await 吗?否则,它会在不等待结果的情况下渲染

标签: react-native fetch react-native-flatlist


【解决方案1】:

您需要将getStatus 的结果存储在组件状态中,就像对患者 JSON 所做的那样。假设您的状态中有一个“统计”对象将患者映射到他们的统计数据,您可以这样做:

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 和可见性更改的回调。

希望对你有帮助……

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-16
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 2022-01-25
    相关资源
    最近更新 更多