【问题标题】:Custom component that makes use of state doesn't update when state changes使用状态的自定义组件在状态更改时不会更新
【发布时间】:2019-05-14 19:31:47
【问题描述】:

我目前在构造函数中设置了一个默认图片源,需要:

constructor(props) {
super(props);
    this.state = {
       name: '',
       pictureSource: require('../assets/images/robot-dev.png')
    };
}

我的自定义组件正在使用图片源作为道具,而我的 TextInput 正在使用名称:

<EditableRoundedImage picture={this.state.pictureSource}/>
<Text style={styles.name}>{this.state.name}</Text>

---Inside EditableRoundedImage---

constructor(props) {
   super(props);
   this.state = {
     image: this.props.picture
   };
}
<Image style={styles.roundedImage} source={this.state.image} />

在 componentDidMount 生命周期方法中,我正在获取一些数据并随后更改图片来源/名称:

this.setState({
      name: jsonResponse.firstName + " " + jsonResponse.lastName,
      pictureSource: {uri: jsonResponse.imageUrl}
    })

*jsonResponse.imageUrl 有以下内容:https://ph-files.imgix.net/b5541240-7da7-4bf0-8dc2-c9e911b283f2?auto=format&auto=compress&codec=mozjpeg&cs=strip

由于某种原因,新获取的图片未显示在应用中,但名称显示。我想知道它是否与 {uri: } 符号有关,或者我正在监督某些事情。

提前致谢!

【问题讨论】:

  • 您可以尝试在 CodeSandBox 中为 react-native here 重现该问题吗?
  • &lt;Image /&gt; 是否包含在 EditableRoundedImage 组件中?我认为显示 EditableRoundedImage 组件的完整代码会有所帮助

标签: javascript react-native components uri


【解决方案1】:

您将this.state.image 分配给图像源。但是您所在的州没有名为image 的属性。会不会是这个问题?

【讨论】:

  • this.state.image 在我存在的 EditableRoundedImage 组件中被调用。您可以看到它是在我发布的第二段代码中创建的
猜你喜欢
  • 1970-01-01
  • 2020-07-18
  • 2021-09-29
  • 1970-01-01
  • 2018-05-21
  • 2023-03-29
  • 1970-01-01
  • 2020-05-01
  • 2021-12-25
相关资源
最近更新 更多