reactjs - axios和数组修改
问题描述
你好我正在寻找一种方法来让我的坐标值在我的新对象数组中恢复,因为我正在使用 react-leaflet 并且 lat 和 long 被恢复。所以我尝试创建一个具有完全相同值的新对象数组,并且只修改坐标数组。
class MapLayer extends Component {
constructor(props) {
super(props);
this.state = {
city: [],
chosenTown: 'Toulouse',
name: CITIES
};
this.handleChange = this.handleChange.bind(this)
}
componentDidMount(){
const toulouse = `https://sportplaces.api.decathlon.com/api/v1/places?origin=1.444209,43.604652&radius=50`
axios.get(toulouse)
.then(res => res.data.data.features)
.then(data => {
const newData = data
newData.map(newData =>{
return {
...newData,
coordinates:[1,0,2],
proximity: 1
}
})
console.log(newData)
})
.then(data => {this.setState({city: data})})
}
componentDidUpdate(){
console.log('test')
}
handleChange(e){
const newFilter = e.target.value
this.setState({chosenTown:newFilter});
}
render() {
const { city } = this.state;
const {chosenTown} = this.state;
const {name} = this.state;
const {handleChange} = this.handleChange
return (
<>
<FilterSelector option={name} handleChange={handleChange} />
<Map center={[43.604652, 1.444209]} zoom={12}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
{city.filter((spot) => spot.properties.address_components.city === chosenTown)
.map((geo) => (
<Marker key={geo.properties.uuid} position={geo.geometry.coordinates} draggable="true">
<Popup>
<Preview geo={geo} />
</Popup>
</Marker>
))}
</Map>
</>
);
}
}
export default MapLayer;
解决方案
您需要存储“Array.map”结果并返回它。在您的代码中:
.then(data => {
const newData = data
newData.map(newData =>{
return {
...newData,
coordinates:[1,0,2],
proximity: 1
}
})
console.log(newData)
})
您的映射数据丢失了,并且您没有返回任何内容,因此将 next作为参数调用.then
。undefined
返回映射的变换,你应该很高兴:
.then(data => {
const newData = data.map(newData => {
return {
...newData,
coordinates:[1,0,2],
proximity: 1
}
});
console.log(newData);
return newData;
})
记住:
Array.map
不会改变数组,而是创建一个新数组。- 每个
.then
承诺都使用先前从 a.then
或中返回的值.catch
。
推荐阅读
- python - Django:类没有“对象”成员
- sql - Oracle listagg on long 值变成了奇怪的字符
- android - Kotlin how to create layout for galaxy z fold2
- c# - Waiting for durable entity value to change
- ruby - rspec - 向测试添加多种类型
- javascript - react - Images return 404 since added proxy
- mysql - 错误代码 2068 本地 infile 文件因访问限制而被拒绝
- ffmpeg - FFMPEG 用于将 RGB 转换为 YUV420 图像的 sws_scale 非常慢
- python - 在 tensorflow 上运行“next_batch”的问题
- apache-spark - 如何防止pyspark在表名中添加双引号