【问题标题】:aws-amplify-react Connect returns undefined data firstaws-amplify-react Connect 首先返回未定义的数据
【发布时间】:2018-11-09 11:27:01
【问题描述】:

我有以下设置:

  • aws-amplify-react
  • 应用同步
  • 创建反应应用程序

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

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

组件示例:

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>
);

【问题讨论】:

    标签: graphql aws-appsync aws-amplify


    【解决方案1】:

    我遇到了同样的问题,我认为 amplify 期望开发人员检查响应是否为 Ready。我通过以下方式解决了它:

    <Connect query={graphqlOperation(someAppSyncQuery)}>
      {this.test}
    </Connect>
    
    
    const test = (appSyncResponseObject: any): any => {
      if (appSyncResponseObject.data == null ||
          appSyncResponseObject.data.getRecords == null) {
          return null;
        } else {
          const records = appSyncResponseObject.data.getRecords;
          return (
            <div>
              <h3>List all records</h3>
              <ul>
                {records.map(
                  (records) =>
                    (<li key={records.uuid}>{records.context}</li>)
                )
                }
              </ul>
            </div>
          )
        }
    }

    【讨论】:

      【解决方案2】:

      AWS API LINK

      上面链接的相关代码sn-p:

      <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 组件的内部不仅带有“数据”,还带有“错误”和“加载”。由于这是一个异步请求,如果您尝试立即返回数据,它不会在那里,但是如果您按照上面的示例进行操作(当然假设您的请求返回数据),您应该很好。

      【讨论】:

        猜你喜欢
        • 2019-09-02
        • 1970-01-01
        • 2021-03-04
        • 2021-02-03
        • 2020-12-28
        • 1970-01-01
        • 1970-01-01
        • 2021-01-30
        • 2020-12-08
        相关资源
        最近更新 更多