我在使用expo从React Native应用程序的存储中调度访问项时遇到困难。
当用户访问组件并列出它时,我想调度我的数据列表功能
const Flows = ({navigation}) => {
const dispatch = useDispatch();
const {invoices, loading, error} = useSelector(state => state.invoiceList);
useEffect(() => {
dispatch(listInvoices());
console.log(`list invoices dispatched`);
}, []);
console.log(`invoices ` + invoices || undefined);
console.log(`loading ` + loading);
console.log(`error ` + error);
然后是渲染。
当我打开这个屏幕时,我得到的日志是
invoices
loading undefined
error undefined
list invoices dispatched
invoices undefined
loading true
error undefined
invoices [object Object],[object Object],[object Object],[object Object],[object Object]
loading false
error undefined
当我试图访问发票中的对象时,问题就出现了——我得到了一个undefined is not an object (evaluating invoices.data)
错误。
我认为这是因为在发票数据被提取并在商店中之前,组件会尝试访问商店更新之前未定义的invoices.data
。然而,尽管最终更新了存储,但这会引发一个错误。
你如何解决这个问题?
首先,验证invoices
是否将列表保持在redux状态。如果是这样,那么遵循:
在访问invoices
列表中的任何值之前,添加对null
或undefined
的检查
const Flows = ({navigation}) => {
const dispatch = useDispatch();
const {invoices, loading, error} = useSelector(state => state.invoiceList);
useEffect(() => {
dispatch(listInvoices());
console.log(`list invoices dispatched`);
}, []);
console.log(`invoices ` + invoices || undefined);
console.log(`loading ` + loading);
console.log(`error ` + error);
// show error UI
if(error){
return <ErrorText />
}
// handle UI if invoices is null/undefined
if(loader || !invoices || invoices.length === 0) {
// show loader
return <Loader />
}
return <List />
}
simple-put可选链接(?.(?。操作员就像。链接运算符,但如果引用为空(空或未定义(,则不会导致错误
这样访问它不会抛出错误
invoices?.data
参考://developer.mozilla.org/en-US/docs/Web/JavaScript/reference/Operators/Optional_chaining