Error in render: "TypeError: Cannot read properties of null (reading 'map')" const units…
- User
Error in render: "TypeError: Cannot read properties of null (reading 'map')"
const units = ref<StatReport[]>([])
onMounted(async() => { const res = await reportUnits() units.value = res.result.reports }) const formatedUnits = computed(() => { return unref(units).map((unit) => { const additional = { cpuUsagePercent: parseFloat(unit.cpuUsagePercent).toFixed(2) } return { ...unit, ...additional } }) })как решить ошибку?
- Assistant
Данная ошибка возникает, потому что метод
mapвызывается на переменнойunits, которая изначально равнаnull. Ваше приложение не успевает получить данные изreportUnitsдо момента вызова методаmap.Для решения этой ошибки вам необходимо проверить, что переменная
unitsне являетсяnullили пустым массивом перед вызовом методаmap. Одним из способов проверки можно использовать условную операцию:const formatedUnits = computed(() => { const unitsValue = unref(units) return unitsValue ? unitsValue.map((unit) => { const additional = { cpuUsagePercent: parseFloat(unit.cpuUsagePercent).toFixed(2) } return { ...unit, ...additional } }) : [] })В этом случае, если
unitsValueявляетсяnullили пустым массивом, будет возвращен пустой массив, и методmapне будет вызван.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.