You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Open Library API返回数据中lccn数组首项以加载图书封面

问题原因

  • JavaScript中数组属于引用类型,typeof运算符对数组执行检测时统一返回object,属于语言固有特性,你可以用Array.isArray(lccn)来准确检测变量是不是数组类型。
  • 你现有代码的核心错误在BookItem组件:你对lccn数组做了全量遍历,遍历得到的firstLccn已经是单个字符串格式的lccn值,你又写firstLccn[0]相当于取字符串的第一个字符,自然不符合预期;且你只需要数组第一项,完全不需要遍历整个数组。

修复方案

直接修改BookItem组件代码即可,同时增加边界判断,避免部分图书不存在lccn字段时页面报错:

export default class BookItem extends Component {
  render() {
    const {title, lccn} = this.props.item;
    // 取lccn首项,不存在时留空可自行替换为默认封面逻辑
    const firstLccn = Array.isArray(lccn) ? lccn[0] : '';

    return (
      <View>
        <View style={styles.cardContainerStyle}>
          <View style={{paddingRight: 5}}>
            {/* 只有存在有效lccn时才渲染封面 */}
            {firstLccn && (
              <Image
                source={{
                  uri: `https://covers.openlibrary.org/b/lccn/${firstLccn}-M.jpg`,
                }}
                style={{width: 100, height: 100}}
              />
            )}
            <Text style={styles.cardTextStyle}>{title}</Text>
          </View>
        </View>
      </View>
    );
  }
}

内容的提问来源于stack exchange,提问作者user16861088

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 04:18:04