反应更新状态中的数组 [英] React Updating Arrays in State

查看:52
本文介绍了反应更新状态中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-native-maps 并尝试绘制多条折线.我在这个结构中分组了状态中的点:

I am using react-native-maps and trying to draw multiple polylines. I have grouped points in this structure in state:

var groups = [{
    Key: 'YELLOW',
    Points: [],
}]

现在我想在 Points 数组中推送 lat/lng 对象,但它给出了对象不可扩展的错误.我尝试使用 [... this.state.groups] 扩展属性,但我无法在其中推送 Points.

Now I want to push lat/lng objects in Points array but it gives object not extensible error. I tried to expand attibutes using [... this.state.groups] but I can't push Points in it.

我有一个单独的数组,其中包含一个类似的结构,其中包含所有点数据.这里的概念是我需要将数据推送到这个组数据结构中,每个点都有延迟,这样折线/路线绘制速度很慢.

I have a separate array which contains a similar structure which has all the points data. The concept here is that I need to push that data in to this group data structure with a delay for each point so the polylines/route draws slowly.

推荐答案

我是这样使用 splice 和 concat 函数的:

I used splice and concat functions in this way:

用于添加

this.setState((state) => {

    var newArray = [...state.cordinates, {
        latitude: point.latitude,
        longitude: point.longitude,
    }];

    return {
        cordinates: newArray,
    };

});

删除:

this.setState((state) => {

    var newArray = [...this.state.cordinates];

    newArray.splice(-1, 1);

    return {
        cordinates: newArray,
    };

});

这篇关于反应更新状态中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆