values.map 不是一个函数 reactjs [英] values.map is not a function reactjs

查看:30
本文介绍了values.map 不是一个函数 reactjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从数据库中获取详细信息,希望将其显示到表格中,但出于最初的目的,我只想在浏览器上显示而没有表格和其他东西.我正在获取 values.map 不是一个函数,但我可以看到打印的值在控制台中

这里使用的是函数组件

导出默认函数 SimpleTable() {const [values, setValues] = useState({});

这里是获取函数

异步函数handleTable(){const res = await fetch("http://localhost:4000/productslist")const 数据 = 等待 res.json()设置值(数据.数据)控制台日志(数据.数据)}

调用 useEffect 上的 fetch 函数

useEffect(()=>{句柄表()},[])

将值渲染到浏览器中

返回 (<div>{console.log(values)}{values.map(v => {return 

{v.productName}{v.productId}{v.productBrand}

})}

);}

这里是错误

未捕获的类型错误:values.map 不是函数

解决方案

你的值的初始状态是一个空对象

来自

const [values, setValues] = useState({});

更新到

const [values, setValues] = useState([]);

因为 Object 没有名为 .map

的方法

也在你的代码中,因为它是一个异步调用,你可以根据状态检查数据是否已加载,你可以添加一个简单的东西是三元检查

{values.length &&values.map(v => {return 

{v.productName}{v.productId}{v.productBrand}

})}

);

所以一旦数组的长度大于零,它就会执行映射函数

使用示例示例Codesandbox>

i am fetchin details from database wanted to display that into the table, but for initial purpose i wanted to just display on browser without table and stuff.. am getting values.map is not a function but i could the see values printed in console

here iam using function component

export default function SimpleTable() {
const [values, setValues] = useState({});

here is the fetch function

async function handleTable(){
const res = await fetch("http://localhost:4000/productslist")
const data = await res.json()
setValues(data.data)
console.log(data.data)
}

calling the fetch function on useEffect

useEffect(()=>{
handleTable()
},[])

Rendering the values into browser

return (
<div>

{console.log(values)}
{values.map(v => {
return  <h4 key={v.idaddproducts}>{v.productName}{v.productId}{v.productBrand}</h4>})}
</div>
);
}

here is the error

Uncaught TypeError: values.map is not a function

解决方案

The initial state of your values is an empty object

From

const [values, setValues] = useState({});

Update to

const [values, setValues] = useState([]);

Since Object doesn't have a method called .map

Also in your code since its a async call you can check based on a state whether data has load or not a simple thing you can add is a ternary check

{values.length && values.map(v => {
return  <h4 key={v.idaddproducts}>{v.productName}{v.productId}{v.productBrand}</h4>})}
</div>
);

so once the array has a length greater than zero only it will execute the map function

Working Codesandbox With Sample Example

这篇关于values.map 不是一个函数 reactjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆