[英]Uncaught TypeError: Cannot read properties of undefined (reading 'filter') JavaScript
I have a problem concern filter in JavaScript can't working.我有一个问题,担心 JavaScript 中的过滤器无法工作。 I'm not sure may because API using long time for response
我不确定可能是因为 API 使用很长时间进行响应
My code :我的代码:
const getDataAll = () =>{
const [machines, setMachines] = useState([])
const getMc = async () =>{
try {
const resMc = await axios.get("My API")
setMachines(resMc.data)
} catch (err) {
console.error(err.message)
}
useEffect(()=>{
getMc()
},[])
const sumData = () =>{
const filterName = machines.data.filter((el) => el.name == "v10turbo")
}
}
Filter have show this alert in some time.过滤器已在一段时间内显示此警报。
And i see time show in browser for API response around 8-9 second follow image below我在浏览器中看到 API 响应的时间显示在 8-9 秒左右,如下图所示
I'm not sure if I got it right.我不确定我是否做对了。 if right please help me with to solve this problem
如果正确,请帮我解决这个问题
The code itself is correct.代码本身是正确的。 But when your component renders, there is no data yet, useeffect works after rerender.
但是当你的组件渲染时,还没有数据,useeffect在重新渲染后起作用。 You need a loading state:
你需要一个加载状态:
const getDataAll = () =>{ const [machines, setMachines] = useState([]); const [loading, setLoading] = useState(true); const getMc = async () =>{ try { const resMc = await axios.get("My API") setMachines(resMc.data) setLoading(false); } catch (err) { console.error(err.message) } finally { setLoading(false); } } useEffect(()=>{ getMc() },[]) const sumData = () =>{ const filterName = machines.data.filter((el) => item.name == "v10turbo") } } if(loading) { return<p>Loading...</p> }
This should fix it.这应该解决它。
I not sure, but this can be helpful我不确定,但这可能会有所帮助
const sumData = useCallback(() =>{
const filterName = machines.data?.filter((el) => item.name == "v10turbo")
}, [machines]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.