You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Axios为对象数组添加值为null的userRating属性

核心问题

Array.prototype.map() 是纯函数,不会修改原数组,只会返回处理后的新数组。你当前的代码没有接收map执行后的返回值,赋值给updatedResponse的仍然是接口返回的原始数据,因此不会新增userRating属性。

修正代码

const movieRequest = () => {
    axios
      .get(key)
      .then((response) => {
        // 接收map返回的处理后新数组
        const updatedResponse = response.data.map((movie) => ({
          ...movie,
          userRating: null,
        }))
        setMovieList(updatedResponse)
      })
      .catch((error) => console.log(error))
  }

可选方案

如果你不需要保留原始数组,也可以用forEach直接遍历修改原数组对象,省去生成新数组的开销:

const movieRequest = () => {
    axios
      .get(key)
      .then((response) => {
        response.data.forEach(movie => {
          movie.userRating = null
        })
        setMovieList(response.data)
      })
      .catch((error) => console.log(error))
  }

注意事项

  • 调用数组方法前建议先校验response.data的类型是否为数组,避免接口返回异常时引发运行报错。

内容的提问来源于stack exchange,提问作者bysiuxvx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:57:00