我想用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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。