如何使用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
相关产品推荐
相关产品推荐

