首页 > 解决方案 > 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='&copy; <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;

标签: reactjsaxiosleafletreact-leaflet

解决方案


您需要存储“Array.map”结果并返回它。在您的代码中:

.then(data => {
  const newData = data
  newData.map(newData =>{
    return {
      ...newData,
      coordinates:[1,0,2],
      proximity: 1
    }
  })
  console.log(newData)
})

您的映射数据丢失了,并且您没有返回任何内容,因此将 next作为参数调用.thenundefined

返回映射的变换,你应该很高兴:

.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

推荐阅读