【问题标题】:Set state not working for image source设置状态不适用于图像源
【发布时间】:2018-06-14 20:29:53
【问题描述】:

我有这样的代码 - 我正在将我的图像保存到正在获取和打印正确 URL 的状态

fetchData = async () => {
this.setState({profilePicUrl: await 
AsyncStorage.getItem('profileImg')});
//here it is printing the right URL
console.log('this.state.profilePicUrl '+this.state.profilePicUrl);
console.log('this.props.profile '+this.props.profile); 
};

但是在同一个组件的render方法中

<Thumbnail source={{uri: this.state.profilePicUrl}} style={{ height: 100, width: null, flex: 1 }} />

这个缩略图没有显示任何内容,在 EXPO XDE 中我看到 source.uri 是一个空字符串

我已经像这样在渲染方法中记录了 profilePicUrl

render() {
console.log('In Render method of Profile');
console.log('In Render method of Profile this.state.profilePicUrl 

'+this.state.profilePicUrl);

并且能够在控制台中获取 url。但是,我看到了这个错误

source.uri 不应为缩略图中的空字符串

这个问题与这个问题类似,因为我也使用 Firebase 来存储和检索图像

Setting image source to Firebase Storage URL with React Native

【问题讨论】:

    标签: javascript image reactjs react-native


    【解决方案1】:

    您需要设置缩略图的高度和宽度。

    【讨论】:

    • 已处理。错误是 source.uri 不应为空字符串,这意味着 this.state.profilePicUrl 为空
    • 那么你应该尝试使用 this.props.profilePicUrl 而不是从 state 获取
    • 这就是设置状态用于重新渲染 DOM,为什么它不能重新渲染图像
    • 好吧,我觉得最初您的 profilepicuri 为空,然后您获取数据,这就是您看到 source.uri 为空消息的原因。您应该尝试在 render 方法中记录,以便在调用 setstate 时知道您的组件是否正在重新渲染
    【解决方案2】:

    看起来可能是因为您正在异步加载图像,因此 react 试图在填充 uri 之前渲染缩略图组件。您可以使用布尔值来跟踪图像是否已被获取并延迟渲染组件。

    这是一个 LazyImage 组件的示例:https://medium.com/@awesomejerry/image-with-react-native-98e7363f6dfe

    【讨论】:

    • 我尝试过这样的事情。 if (img) { thumbnail = console.log('Thumnail img') } else { thumbnail = null; } 即使那样它也没有工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 2012-08-14
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多