【发布时间】:2021-03-24 14:57:01
【问题描述】:
我正在尝试通过从 AsyncStorage 获取值来呈现数据数组。但是当我尝试映射数组时,首先调用渲染并显示map of undefined。这是代码:
const [myCosts, setMyCosts] = useState([]);
useEffect(() => {
console.log('useeffect')
readData();
}, [])
const readData = async () => {
try {
const expenseValue = await AsyncStorage.getItem('COSTLIST')
setMyCosts(expenseValue);
} catch (e) {
alert('Failed to fetch the data from storage')
}
}
if (myCosts === []) {
return (
<View style={styles.activityIndicatorContainer}>
<ActivityIndicator animating={true}/>
</View>
);
} else {
return(
<View>
{myCosts.map(cost => {
return (
<Text style={{backgroundColor:'#f2e3df',color:'#000',padding:10}}>
{cost.name}
</Text>
)
})
}
</View>
)
}
我也添加了条件。但它仍然给出错误。还能做什么?
【问题讨论】:
-
很明显,截至
setMyCosts(expenseValue);,expenseValue是undefined。所以这就是你需要调试的。 -
旁注:此检查将始终失败:
if (myCosts === []) {数组是对象,没有数组是=== [],因为没有其他数组与您使用[]创建的数组相同。如果要检查空数组,可以使用if (!myCosts.length) {或if (myCosts.length === 0) { -
expenseValue 不是未定义的。如果我尝试映射,则它显示未定义,否则它在控制台上显示数据正常。 @T.J.克劳德
-
在您显示的代码中,从字面上看,获得您描述的
map错误的唯一方法是,如果expenseValue在该调用中是undefined。所以要么问题出在你没有显示的代码中,要么expenseValue在那个调用中是undefined。