我有一個React JS專案,有以下問題:
在狀態中,我有一個decorators陣列和一個polyPaths陣列,即:
在狀態中,我有一個裝飾器陣列和一個polyPaths陣列,即:
this.state = {
decorators = [],
polyPaths = [],
}
在我的渲染方法中,我有以下一段代碼:
{this.state。 polyPath.map((polyline, index) => {
return (
<PolylineDecorator。
patterns={arrow_blue}。
位置={polyline}
color={"blue"}。
opacity={{0.5}"}。
key={index}
addDecorator={this.addDecorator}。
currDecorators={this.state.decorators}。
checkIfSamePath={this.checkIfSamePath}。
/>
);
})}
這將映射多段線并渲染一個多段線裝飾器。
在PolylineDecorator組件中,我呼叫以下方法:
addDecorator = (dec) =>/span> {
//為狀態添加裝飾器。
this.setState({
decorators: [...this.state.decorators, dec] 。
})
}
現在我的問題是,由于某些原因,如果polyPaths中已經有2個現有專案,那么只有第二個裝飾器將被保存到狀態中,即:裝飾器將只有1個元素。
我不確定為什么會發生這種情況(也許是因為它再次設定狀態的速度太快了?),我可以做些什么呢?
我知道addDecorator函式確實被呼叫了兩次,每個裝飾器都是如此,只是只保存了最后一個?
謝謝
uj5u.com熱心網友回復:
addDecorator = (dec) =>/span> {
//為狀態添加裝飾器。
this.setState({
decorators: [...this.state.decorators, ... dec]
})
}
在兩個陣列上使用spread運算子,否則你只是把新的陣列直接放在舊的陣列里面
。或者如果你想放另一個全新的陣列,就這樣做
。
addDecorator = (dec) => {
//為狀態添加裝飾器。
this.setState({
decorators: dec
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/306996.html
標籤:
