aws-amplify-react Connect首先返回未定义的数据 [英] aws-amplify-react Connect returns undefined data first

查看:106
本文介绍了aws-amplify-react Connect首先返回未定义的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下设置:

  • aws-amplify-react
  • appsync
  • create-react-app

并遵循此文档: https://aws.github.io/aws-amplify/media/api_guide#connect

与在文档中一样,在返回正确的数据之前,渲染它会给我2x undefined数据.这会破坏应用程序,因为无法访问嵌套字段(在我的示例中,例如getRoom.id).

As in the doc, rendering this gives me 2x undefined data before returning the correct data. This breaks the app, as nested fields (in my example, e.g. getRoom.id) cannot be accessed.

组件示例:

export const AppSyncTest = () => (
  <Connect query={graphqlOperation(query)}>
    {({ data: { getRoom } }) => {

      console.log(getRoom); // returns undefined 2x before data is there

      if (!getRoom) { // without this, app breaks
        return 'why? (can even happen if loading is false)';
      }

      return (
        <div className="App">
          <header className="App-header">
            <h1 className="App-title">Welcome to IntelliFM WebApp</h1>
          </header>
          <p className="App-intro">
            Found room {getRoom.id} with label {getRoom.label} and description{' '}
            {getRoom.description}
          </p>
        </div>
      );
    }}
  </Connect>
);

推荐答案

请参见 AWS API LINK

以上链接中的相关代码段:

Relevant code snippet from above link:

<Connect query={graphqlOperation(queries.listTodos)}>
            {({ data: { listTodos }, loading, error }) => {
                if (error) return (<h3>Error</h3>);
                if (loading || !listTodos) return (<h3>Loading...</h3>);
                return (<ListView todos={listTodos.items} /> );
            }}
        </Connect>

请注意,Connect组件的内部不仅包含数据",还包含错误"和加载".由于这是一个异步请求,因此如果您尝试立即返回数据,它将不会在那里,但是如果您按照上面的示例所示进行操作(假设您的请求当然返回了数据),那么您应该很好.

Notice that the inside of the Connect component comes with not just 'data', but also 'error' and 'loading'. Since this is an asynchronous request, if you try to return data immediately, it will not be there, but if you do as the example above shows (assuming your request returns data of course), you should be good.

这篇关于aws-amplify-react Connect首先返回未定义的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆