React 中 img 标签中的 onError

onError in img tag in React

我想用 React 中的默认图像替换损坏的 link。我通常会为此使用 onerror 但它没有按预期工作。具体来说,我反复出现 "Cannot update during an existing state transition (such as within render)." 的错误 最终,默认图像出现了,但需要很长时间(多次打印此错误)。这是在这里提出的一个非常相似的问题:。我尝试了这个解决方案(最上面的一个,没有使用 jQuery),但它导致了所描述的错误。我想 onError 一定是不断被触发,从而导致不断重新渲染。还有其他选择吗 solutions/fixes?

   import React from 'react';
import { connect } from 'react-redux';
//import AddImageModal from '../components/AddImageModal.js';
import Button from 'react-bootstrap/lib/Button';
//import { getPostsByUserId } from 'actions'
import Posts from '../components/Posts.js';
var Modal = require('react-modal');
require('../../styles/AddImageModal.scss');
import { save_post } from '../actions';

 const customStyles = {
  content : {
    top                   : '50%',
    left                  : '50%',
    right                 : 'auto',
    bottom                : 'auto',
    marginRight           : '-50%',
    transform             : 'translate(-50%, -50%)'
  }
};

var MyWallScreen = React.createClass({

  getInitialState: function() {
    return { 
      modalIsOpen: false,
      imageUrl: "" 
    };
  },

  openModal: function() {
    this.setState({modalIsOpen: true});
  },

  afterOpenModal: function() {
    // references are now sync'd and can be accessed. 
    this.refs.subtitle.style.color = '#f00';
  },

  closeModal: function() {
    this.setState({modalIsOpen: false});
  },

  setUrl: function(e,val) 
  {
    if (e.keyCode === 13) 
        {
          this.setState({
            imageUrl: val
          });
        }
  },

  resetImageUrl: function()
  {
    this.setState({
      imageUrl: ""
    });
  },

  onError: function() {
    this.setState({
      imageUrl: "default.jpg"
    });
  },


  render: function() {
    const { userPosts, dispatch } = this.props;
    return (
      <div>
        <button onClick={this.openModal}>Add Image</button>

        {/* The meat of the modal. */}
        <Modal
          isOpen={this.state.modalIsOpen}
          onAfterOpen={this.afterOpenModal}
          onRequestClose={this.closeModal}
          style={customStyles} >

        <div className="modalBox">
          <h2 className="modalBanner">Add an image link</h2>
          <input ref="urlInput" 
                className="modalInput"
                onKeyDown={e=>this.setUrl(e,this.refs.urlInput.value)}/>
          {this.state.imageUrl ?
            <img className="modalImage" 
                  src={this.state.imageUrl}
                  onError={this.onError()}/>
            :<div className="modalImage"></div>
          }
          <div>
            <Button className="modalButton" bsStyle = "success" 
                onClick = {() => {
                dispatch(save_post(0,this.state.imageUrl));
                this.closeModal();
                this.resetImageUrl();
                }}>
                Post
            </Button>
            <Button className="modalButton" bsStyle = "danger" 
                onClick = {() => {
                  this.closeModal();
                  this.resetImageUrl();
                }}>
                Cancel
            </Button>
          </div>
        </div>
        </Modal>


        <Posts posts={userPosts}/>
      </div>
    );
  }
});


function mapStateToProps(state, ownProps) {
  return {
    userPosts: state.posts[0]
  }
}


MyWallScreen = connect(mapStateToProps)(MyWallScreen);

export default MyWallScreen;

代码正在调用 this.onError 而不是传递对它的引用。对 render 的每次调用都在调用 this.onError()。删除括号,看看是否可以解决问题:

<img className="modalImage" 
  src={this.state.imageUrl}
  onError={this.onError()}/> // `onError` is being called here

固定版本:

<img className="modalImage" 
  src={this.state.imageUrl}
  onError={this.onError}/> // `onError` is being passed as a reference here

您可以替换损坏的图像 link,而无需保持图像 url 处于状态。

<img
 onError={(event)=>event.target.setAttribute("src","default-image-link")}
 src="image-broken-link"
/>