我有一个简单的问题,我不知道为什么会发生。我需要从localStorage中呈现一些内容,但这个值是在用户搜索内容时设置的。。这样我就可以在下一次搜索中;某事";已搜索。
const Home = () => {
const { contextState } = useContext(ContentContext)
const [valInStorage, setValInStorage ] = useState({})
useEffect(()=>{
const storageValue = localStorage.getItem('values')
if(storageValue !== null && storageValue !== undefined){
setValInStorage(JSON.parse(storageValue))
}
},[])
console.log(valInStorage)
let valInfo = Object.values(contexState).filter(item => typeof item === "object")
return (
<div className={`siteContent`}>
<SearchBar />
<Fragment>
<h2>Result</h2>
{
valInfo.map( item => ( item !== null ?
<Card key={item.id} data={item}/> :
<h3 key={1}>No item to show</h3>)
)
}
<h2>Last value searched</h2>
{/*the error occurs when the card component receives an undefined value. */}
{contextState !== undefined ? (<Card data=
{valInStorage}/>):(<p>Nothing here</p>)}
</Fragment>
对我来说奇怪的是,我告诉你,如果值未定义,它将呈现其他东西。。。我也试过:
{contextState !== undefined && (<Card data={valInStorage}/>)}
不断抛出错误。我理解错误发生的原因。发生这种情况是因为我将一个未定义的值传递给Card组件。我不明白的是为什么条件句不起作用。
我只是想,如果我像往常一样应用一个简单的控制结构,它会防止组件接收到未定义或null值。
您在Object.values中传递的是contexState
,而不是可能导致错误的contextState
。
至于您的状态,它可能也有导致问题的错误数据,您需要console.log(valInStorage)
并在此处查看其值以确定问题。
最后,确保您的useEffect
在商店更新时运行,您需要在localStorage更新时传递一个道具,并将该道具设置为useEffect的依赖项。目前,当组件挂载时,useEffect只工作一次。