如何从Airtable数据库提取图像?

时间:2019-04-15 17:36:45

标签: reactjs airtable

当我尝试编译代码时,出现错误:

Error Image

我正在关注一个教程,唯一的区别是Airtable中每个列/字段的名称。我的项目应该可以,但不能。我忘了特别声明什么吗?有没有更简便的方法从Airtable获取图像? React Airtable Tutorial

import React, { Component } from 'react';
import { Container, Row, Col, Card, CardImg, CardText, CardBody,
  CardTitle, CardSubtitle, Button } from 'reactstrap';
import './main.css';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      skills: [],
    };
  }

  componentDidMount() {
    fetch('https://api.airtable.com/v0/appXy4JgrvUicfB5F/Resources?api_key=keyE0exOkvaAnJeS0')
    .then((resp) => resp.json())
    .then(data => {
       console.log(data);
       this.setState({ skills: data.records });
    }).catch(err => {
      // Error 
    });
  }

  render() {
    return (
      <div className="container">
        <Row>
          <Col>
            {this.state.skills.map(skill => <Roster {...skill.fields} /> )}
          </Col>
        </Row>
      </div>
    );
  }

}

export default App;

const Roster = ({ Name, Service, LinkedIN, GitHub, Twitter, Facebook, Picture }) => (
      <div className="card">
        <div className="card-body">
          <img className="card-img-left" src={Picture[0].url} />
          <h5 className="card-title">{Name}</h5>
          <p className="card-subtitle">{Service}</p>
          <p className="card-text">
            <small className="text-muted"><a href={LinkedIN}><i class="fab fa-linkedin"></i></a></small>&nbsp;
            <small className="text-muted"><a href={GitHub}><i class="fab fa-github-square"></i></a></small>&nbsp;
            <small className="text-muted"><a href={Twitter}><i class="fab fa-twitter-square"></i></a></small>&nbsp;
            <small className="text-muted"><a href={Facebook}><i class="fab fa-facebook"></i></a></small>&nbsp;
          </p>
        </div>
      </div>
);

1 个答案:

答案 0 :(得分:1)

您使用的Airtable API在许多对象中没有Picture属性,并且由于图片是Picture[0],因此在尝试访问undefined时它们将失败。

如果您没有所有对象的图像,那么简单的方法是在渲染之前先检查是否有Picture

{Picture && <img className="card-img-left" src={Picture[0].url} />}

Demo on Stackblitz