如何将数据添加到数据源而不是替换?

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

我正在开发一个本机应用程序,在接收来自获取请求的数据时我需要在列表视图中显示它,我收到了我想要添加到以前接收的数据的每个提取数据,但我的代码只是替换它,我是新手,对原生和JavaScript做出反应,所以请善解释如何实现它

fetch("http://example.com/getDataFromIndex.php", {
        method: 'POST',
        headers: new Headers({
            'Content-Type': 'application/x-www-form-urlencoded', // <-- Specifying the Content-Type
        }),
        body: params // <-- Post parameters
    }).then((response) => response.json())
        .then((responseJson) => {

            this.setState({
                isLoading: false,
                dataSource: responseJson.data,
            }, function(){

            });

        })
        .catch((error) =>{
            console.error(error);
        });

我想将数据附加到dataSource而不是只替换旧的数据。

javascript reactjs react-native
2个回答
1
投票

假设dataSourceresponseJson.data都是数组,你可以concat他们。

this.setState({
  isLoading: false,
  dataSource: Object.assign(this.state.dataSource).concat(responseJson.data)
});

1
投票

您应该使用更新的ECMAScript 6的object rest spread,如下所示:

this.setState({
                isLoading: false,
                dataSource: {...this.state.dataSoure, ...responseJson.data}
            }, function(){
            // do something after `setState` has occurred (asynchronously)
        })
© www.soinside.com 2019 - 2024. All rights reserved.