javascript – 在reactjs中发生状态更改后调用函数
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 在reactjs中发生状态更改后调用函数,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2347字,纯文字阅读大概需要4分钟。
内容图文
我的问题是这个.我有两个组成部分.第一个组件是图像裁剪器.第二个组件是我应该显示裁剪图像的组件.
我面临的问题是我可以将裁剪后的图像传递给我的第二个组件,但我必须按下裁剪图像的按钮并传递给第二个组件,两次.在第二次单击时,只有我的图像传递给第二个组件.但我只能通过一次单击在第一个组件中显示裁剪的图像.我认为这种情况正在发生,因为在反应状态下,状态变化不会立即发生.那么我该如何解决这个问题呢.
我的方法是在第一个组件中创建一个prop函数this.props.croppedImage(this.state.preview.img);这里this.state.preview.img是裁剪后的图像.在第二个组件中,我通过调用prop函数获得裁剪后的图像.
我的代码
第一部分(裁剪)
class CropperTest extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "beautiful",
scale: 1,
preview: null,
}
this.handleSave = this.handleSave.bind(this);
}
handleSave = () => {
const img = this.editor.getImageScaledToCanvas().toDataURL();
this.setState({
preview: {
img,
scale: this.state.scale,
}
})
this.props.croppedImage(this.state.preview.img);
}
setEditorRef = (editor) => {
this.editor = editor
}
render() {
return (
<div>
<div className="overlay"></div>
<div className="crop_div">
<AvatarEditor
image={this.props.cropImage}
ref={this.setEditorRef}
width={450}
height={450}
border={50}
color={[255, 255, 255, 0.6]} // RGBA
scale={this.state.scale}
rotate={0}
/>
</div>
<div className="zoom_slider text_align_center">
<input className="crop_btn" type='button' onClick={this.handleSave} value='Save'/>
</div>
</div>
)
}
}
export default CropperTest;
第二部分
在这里,我基本上做了以下几点.
<CropperTest croppedImage = {this.getCroppedImg}/>
getCroppedImg(img){
alert("Perfect Storm");
this.setState({
previewImg:img
})
}
解决方法:
I think it is happening because in reactjs state changes are not occurring immediately. So how can i fix this?
setState(updater,[callback])
setState()
enqueues changes to the component state.
ThesetState
doesn’t immediately update the state.setState()
does not always immediately update the component. It may batch or defer the update until later. This makes readingthis.state
right after callingsetState()
a potential pitfall.Instead, usecomponentDidUpdate
or asetState
callback(setState(updater, callback))
在setState回调中调用this.props.croppedImage.您将获得组件状态的更新值.在你的情况下,它的this.state.preview
this.setState({
preview: {
img,
scale: this.state.scale,
}
}, () => {
this.props.croppedImage(this.state.preview.img);
})
内容总结
以上是互联网集市为您收集整理的javascript – 在reactjs中发生状态更改后调用函数全部内容,希望文章能够帮你解决javascript – 在reactjs中发生状态更改后调用函数所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。