【问题标题】:TypeError: values.map is not a function [closed]TypeError:values.map不是一个函数[关闭]
【发布时间】:2019-08-24 20:56:44
【问题描述】:

我正在尝试映射object,但同时它给了我以下错误:TypeError: values.map is not a function。我是 React 开发的新手。

我在Redux中使用这个方法method

代码

export function createEvent(values) {
  let modifyValue = values.map(newValue => {
    return {
      subject: newValue.id,
      taskType: newValue.tasktype,
      time: newValue.time,
      date: newValue.date,
      notes: newValue.notes,
      createdAt: newValue.createdAt,
      updatedAt: newValue.updatedAt,
      deletedAt: newValue.deletedAt,
      userId: newValue.userId,
      customerId: localStorage.getItem("customerValue"),
      start: newValue.start,
      end: newValue.end
    };
  });
  return dispatch => {
    axios
      .post("api/diary/create", modifyValue)

      .then(response => {
        return dispatch({ type: SET_DIARY_TASK_SUCCESS, data: response });
      })

      .catch((xhr, status, err) => {
        return dispatch({ type: SET_DIARY_TASK_FAILURE, data: xhr });
      });
  };
}

【问题讨论】:

  • 您是否检查过map 之前的值中有哪些数据?
  • 什么是values,它来自哪里?
  • @NeelRathod 对象
  • @Cristy It 对象
  • 当我在本地存储中控制台或存储values 时,它会给我结果[object object]

标签: javascript reactjs ecmascript-6 react-redux javascript-objects


【解决方案1】:

对象没有 .map 方法。

您可以使用Object.keysObject.values 创建一个数组,然后对其进行映射。

const obj = {
  1: "first value",
  2: "second value",
  3: "third value"
}

Object.keys(obj).map((el) => {
  console.log(el);
})

Object.values(obj).map((el) => {
  console.log(el);
})

【讨论】:

  • 错误消失了,但我的对象值没有到来。它给了我空值
  • 在这种情况下,您首先需要检查值的存在性 (if(values) { ...} else { ...Error Handler })
【解决方案2】:

Array.prototype.map() 用于遍历数组并创建新数组。如果 values 是一个平面对象,可以通过以下方式显式访问它的属性:

values.propertyName

你的情况:

let modifyValue = {
      subject: values.id,
      taskType: values.tasktype,
      time: values.time,
      date: values.date,
      notes: values.notes,
      createdAt: values.createdAt,
      updatedAt: values.updatedAt,
      deletedAt: values.deletedAt,
      userId: values.userId,
      customerId: localStorage.getItem("customerValue"),
      start: values.start,
      end: values.end
    };

【讨论】:

  • @Jackobec 你能看看我的例子并用正确的版本修改它吗?
  • 没问题,看上面的代码
  • 意思是,我不想用地图?
  • 如果值中只有一个对象,则不需要 .map()
  • 我正在获取值,但数据未发送到服务器。我收到错误500 Internal Server Error
【解决方案3】:

首先,.map() 方法在array 上工作,在您的情况下,您首先需要检查values 是否在数组([])形式与Array.isArray(values),如果它是结果true 这意味着它是数组形式,那么你可以使用.map(),或者如果它是false,那么确保调用函数以数组形式传递它。

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 2020-06-24
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多