我想用react中的默认图像替换断开的链接.我通常会使用onerror,但它没有按预期工作.具体来说,我得到了“在现有状态转换期间无法更新(例如在渲染中)”的重复错误.最终,出现默认图像,但需要很长时间(此错误的许多打印).这是一个非常类似的问题:
react.js Replace img src onerror.我尝试了这个解决方案(排名第一,不使用jQuery),但它导致了所描述的错误.我猜onError必须不断被触发,从而导致不断重新渲染.任何替代解决方案/修复?
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