【发布时间】:2021-07-18 07:01:45
【问题描述】:
我在通过带有对象的数组进行映射时遇到问题,我找不到问题所在,但我认为它是因为异步,但我希望你看看它。
我收到两条错误消息,我不知道它们是否相关:
TypeError: Cannot read property 'map' of null1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
import {useState, useEffect} from 'react';
// import styled from 'styled-components';
export default function Admin() {
const [quotes, setQuotes] = useState(null);
const get_all_quotes = async () => {
const {data, error} = await supabase
.from('quotes_en')
.select('quote')
console.log(data);
if (error) console.table(error)
setQuotes(data)
}
useEffect(() => {
get_all_quotes()
}, [])
return (
<div>
{quotes.map(({id, quote}) => {
return <p key={id}>{quote}</p>
})
}
</div>
)
}
【问题讨论】:
-
quotes初始状态为null,无法映射。session是什么? -
是的会话是检查是否有人登录,但这没关系,我删除它谢谢
-
@DrewReese 那么解决方法和方法是什么?
-
如果状态未完成,我喜欢提前返回。例如。
if (!quotes) return (<div>Loading...</div>); return (.....。如果不需要加载指示器,也可以只返回 null,因此在这里保持初始状态为 null 是合乎逻辑的。 -
我喜欢提前返回有几个原因,1. 使用空数组仍然会导致无意义的渲染,2. 如果您确实想要实现加载指示器,它会很好而且很干净。 3. 使用 null 您还可以免费获得更多状态 jnfo,这里的空默认数组打破了这一点。
标签: javascript reactjs use-state