Redux Data Fetch 和 Rendering 同时发生 React Native

Redux Data Fetch and Rendering Happens at the same time React Native

我在使用 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

当我尝试访问 invoices 中的对象时出现问题,我收到 undefined is not an object (evaluating invoices.data) 错误。

我认为是因为在获取发票数据并在商店中之前,该组件会尝试访问商店更新之前未定义的 invoices.data。但是,尽管最终存储已更新,但这会引发错误。

你是怎么解决这个问题的?

simple put Optional chaining (?.), ?.运算符就像 .链接运算符,除了如果引用为空(null 或未定义)

而不是导致错误

这样访问不会报错

invoices?.data

参考://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

首先,验证 invoices 是否将列表保存在 redux 状态。如果是这样,请关注:

在访问 invoices 列表中的任何值之前,添加对 nullundefined

的检查

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 />
 }