【问题标题】:Changing the value of an element in an Array which is in another Array in React更改 React 中另一个数组中的数组中元素的值
【发布时间】:2020-10-21 09:25:51
【问题描述】:

我正在尝试使用 React 更改另一个数组中的数组的值。

这是我的数组:

routes = [
    {
        id: 1,
        points: [{id, address, status}, {id, address, status},]
    },
    {
        id: 2,
        points: [{id, address, status}, {id, address, status},]
    },
]

以及我是如何设置的。当用户点击“接受”时,该特定点的状态应该会改变。

{routes.map((route, i) => (
    <div>...</div>
    {route.points.map((point, i) => (
        <Button onClick={() => this.onAcceptClicked(route.points)>Accept</Button>
    ))}
))}

我在这里尝试更改值,但我遗漏了一些东西或做的一切都完全错误。该特定点的状态应设置为 2。

onAcceptClicked = (points) => {
    const myNewArray = Object.assign([...points], {
        [index]: {
            ...deliveryPoints[index],
            status: 2
        }
    });
    //this.setState({ points: myNewArray }); ... not sure how to do this part
}

【问题讨论】:

    标签: javascript arrays reactjs react-native


    【解决方案1】:

    您将不得不更新该州的所有路线。

    因为你已经有了索引,你可以跳过查找部分

    {routes.map((route, i) => (
        <div>...</div>
        {route.points.map((point, j) => (
            <Button onClick={() => this.onAcceptClicked(route.points,i,j)>Accept</Button>
        ))}
    

    并更新如下状态的路由(i 是路由数组中项目的索引,j 是点数组中项目的索引)

    onAcceptClicked = (points,i,j) => {
        const myNewArray = [...this.state.routes];
        myNewArray[i].points[j]={...myNewArray[i].points[j],status:2};
        this.setState({ routes: myNewArray }); 
    }
    
    ))}
    

    【讨论】:

    • 不,我的意思是您需要将整个结构再次创建到必须进行更新的级别,而不仅仅是顶层。需要这样做以确保如果嵌套元素作为道具向下传递,它将被识别为已更改。在您的回答中,您将顶级数组替换为一个正确的新数组,但在该数组中您仍在改变对象而不是替换它。
    • 这在大多数应用程序中可能不是问题,就像父级重新渲染它会重新渲染其子级一样。但是,如果一个孩子对它的道具进行了浅显的比较,并且其中一个道具是嵌套对象,它可能会破坏。
    • 和设置状态前newArray的值?
    • 我只是不明白..我的方式完全相同,而且两者都在改变..一旦我弄清楚了,我会告诉你的,谢谢你所做的一切。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    相关资源
    最近更新 更多