首页 文章

React - 尝试更改<img> src属性

提问于
浏览
3

我试图在AJAX调用数据库后更改元素的src属性 . 我有一个在 getDefaultProps() 中定义的默认图像网址,但在AJAX调用之后图像不会改变 .

PictureWidget 是控制状态的 Section 组件的子组件(它还将dataSource和dataSourceParams传递给 PictureWidget ) . 我不确定我是否可以使用本地状态 PictureWidget 所以我试图通过道具来做 .

这是我的代码:

var PictureWidget = React.createClass({

getDefaultProps: function() {
  return {
    url: 'https://d2o57arp16h0eu.cloudfront.net/echo/img/no_image_available.png'
  }
},

componentDidMount: function() {
  this.componentDidUpdate();
},

componentDidUpdate: function() {

  // Grab img URL from DB
  var postData = {
    dataSource: this.props.params.dataSource,
    dataSourceParams: this.props.dataSourceParams
  };

  $.ajax({
    type: 'POST',
    url: ajax_endpoint,
    cache: false,
    data: postData,
    dataType: 'json',
    success: function(response) {
      if (response.data.length > 0) {
        this.updateImage(response.data[0][0]);
      }
    }.bind(this),
    error: function(response) {
      this.render();
    }
  });

},

updateImage: function(url) {
  console.log("Updating props.url with " + url);
  this.props.url = url;
  this.render();
},

render: function(imageURL) {
  console.log("Rendering img " + this.props.url);

  return React.createElement('div', {className: ' pure-u-' + this.props.columns},
    React.createElement('div', {className: 'picture-widget'},
      React.createElement('img', {src: this.props.url})
    )
  )
}
});

这是我的控制台日志(原谅我格式不佳,仍然是Overflow的新手):

Rendering img https://d2o57arp16h0eu.cloudfront.net/echo/img/no_image_available.png
Updating props.url with http://vignette3.wikia.nocookie.net/animalcrossing/images/4/49/Tumblr_lvrcmvCpsS1qbeyouo1_500.jpg/revision/latest
Rendering img http://vignette3.wikia.nocookie.net/animalcrossing/images/4/49/Tumblr_lvrcmvCpsS1qbeyouo1_500.jpg/revision/latest

最初的 render() 抓取了默认的URL,但在AJAX调用 this.props.url 确实更新到新值之后,我怀疑 React.createElement('img', {src: this.props.url}) 是麻烦制造者 . 我不能这样更新src属性吗?

1 回答

  • 1

    这就是国家的目的 . 尝试使用 getInitialState 而不是 getDefaultProps 并使用 setState()url 绑定到 this.state .

    getInitialState: function() {
      return {
        url: 'https://d2o57arp16h0eu.cloudfront.net/echo/img/no_image_available.png'
      };
    },
    
    updateImage: function(url) {
      console.log("Updating state.url with " + url);
      this.setState({ url: url });
    }
    

相关问题