繁体   English   中英

如何从 fetch 中获取 uri?

[英]How can I get the uri from the fetch?

我想在应用程序中缓存图像,以便它们可以更快地加载。 我发现的教程使用了 Expo 的FileSystem ,但我没有使用 expo,所以我找到了react-native-file-access 挂载后,代码应该检查图像是否存在,如果不存在,则下载图像。 我试过了,但我似乎无法让它工作。

import React, {Component} from 'react';
import {Image} from 'react-native';
import shorthash from 'shorthash';
import {Dirs, FileSystem} from 'react-native-file-access';

export default class CacheImage extends Component {
  state = {
    source: null,
  };

  componentDidMount = async () => {
    const {uri} = this.props;
    const name = shorthash.unique(uri);
    const path = `${Dirs.CacheDir}/${name}`;

    const image = await FileSystem.exists(path);
    if (image.exists) {
      this.setState({
        source: {
          uri: image.uri,
        },
      });
      return;
    }

    /* Download image if one doesn't exist */
    const newImage = await FileSystem.fetch(uri, {path: path})
      .then(response => {
        JSON.stringify(response);
      })
      .then(data => data);

    this.setState({
      source: {
        uri: newImage.uri,
      },
    });
    console.log('URI: ', this.state.source);
  };

  render() {
    return <Image style={this.props.style} source={this.state.source} />;
  }
}

问题来自这里

const newImage = await FileSystem.fetch(uri, {path: path})
      .then(response => {
        JSON.stringify(response);
      })
      .then(data => data);

使用时忘记返回 {}

const newImage = await FileSystem.fetch(uri, {path: path})
      .then(response => {
        return JSON.stringify(response);
      })
      .then(data => data);

我返回了没有JSON.stringify()response

const newImage = await FileSystem.fetch(uri, {path: path})
      .then(response => {
        return response;
      });

this.setState({
      source: {
        uri: newImage.url,
      },
    });

而且我还删除了第二个.then()因为我仍然得到url而不添加它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM