【问题标题】:Redux Data Fetch and Rendering Happens at the same time React NativeRedux 数据获取和渲染同时发生 React Native
【发布时间】:2022-01-01 16:54:34
【问题描述】:

我在使用 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。但是,尽管最终存储已更新,但这会引发错误。

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

【问题讨论】:

    标签: reactjs react-native redux react-redux


    【解决方案1】:

    首先,验证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 />
     }
      

    【讨论】:

    • 谢谢 - 这确实很有用
    【解决方案2】:

    简单把可选链(?.), ?.运算符就像 .链接运算符,除非引用为空(null 或未定义)而不是导致错误

    这样访问不会报错

    invoices?.data
    

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

    【讨论】:

    • 谢谢。您是否碰巧知道这是否是执行此操作的标准方式?
    • 顺便说一句,我仍然只是得到空数据,因为在设置存储后组件不会重新呈现。我正在使用 useeffect 这样做:useEffect(() =&gt; { dispatch(listInvoices()); console.log(list invoices dispatched); }, [dispatch]);
    • 在 useEffect 第二个参数数组中传递发票,而不是 dispatch,然后尝试。
    • useEffect(() => { dispatch(listInvoices()); console.log(list invoices dispatched); }, [invoices]);这样做,当发票变量中没有数据时,您需要向加载程序显示类似的内容
    • 试过了。这会创建一个循环,useEffect 不断运行。我认为会有一种更通用的方法来执行此操作,因为任何人都需要从应用程序页面中的存储访问数据点。你知道你通常是怎么做的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多