远程图像未在Android上使用React Native重定向

问题描述:

Android上的React Native存在长期存在的问题,如果uri发出重定向,<Image/>组件将不会加载图像。例如:远程图像未在Android上使用React Native重定向

<Image source={uri: 'https://example.com/image.jpg'}/> 

如果https://example.com/image.jpg响应以重定向(301,302等),以https://example.com/redirect.jpg<Image/>组件将不加载图像。

可以加载重定向后的图片吗?

虽然<Image/>组件不遵循重定向,但获取并且可以用于获取新的uri。

export const getRedirect = async (uri)=>{ 
    const response = await fetch(uri) 
    const data = await response 
    return (data.status === 200 ? data.url : '') 
} 

这然后可以在一个新的组件可以使用这样的:

class RedirectImage extends React.PureComponent { 
    constructor(props) { 
     super(props) 
     this.state = {uri: ''} 
    } 

    componentDidMount() { 
     getRedirect(this.props.uri).then((uri)=>{ 
      this.setState({uri: uri}) 
     }) 
    } 

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

RedirectImage.propTypes = { 
    uri: PropTypes.string.isRequired, 
} 

export default RedirectImage 

现在,作为期望<RedirectImage uri={'https://example.com/image.jpg'}/>将显示https://example.com/redirect.jpg