javascript 在reactjs中发生状态变化后调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45992682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:21:53  来源:igfitidea点击:

Calling functions after state change occurs in reactjs

javascriptreactjsprop

提问by CraZyDroiD

My question is this. I have two components. First component is an image cropper. Second component is the one that i should display the cropped image.

我的问题是这个。我有两个组件。第一个组件是图像裁剪器。第二个组件是我应该显示裁剪图像的组件。

The problem i'm facing is i can pass the cropped image to my second component but i have to press the button that crops the image and pass to the second component, twice. On the second click only my image is passing to the second component. But i can display the cropped image in the first component only by one click. I think it is happening because in reactjs state changes are not occurring immediately. So how can i fix this.

我面临的问题是我可以将裁剪后的图像传递给我的第二个组件,但我必须按两次裁剪图像并传递给第二个组件的按钮。在第二次单击时,只有我的图像传递给第二个组件。但是我只需单击一下就可以在第一个组件中显示裁剪后的图像。我认为它正在发生,因为在 reactjs 状态更改不会立即发生。那么我该如何解决这个问题。

My approach was to create a propfunction in the 1st component as this.props.croppedImage(this.state.preview.img);here this.state.preview.imgis the cropped image. And in the 2nd component i'm getting the cropped image by calling the prop function.

我的方法是prop在第一个组件中创建一个函数,因为this.props.croppedImage(this.state.preview.img);this.state.preview.img是裁剪后的图像。在第二个组件中,我通过调用 prop 函数获取裁剪后的图像。

My code

我的代码

1st component (cropper)

第一个组件(裁剪器)

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;

2nd component

第二个组件

Here i'm basically doing the following.

在这里,我基本上是在做以下事情。

  <CropperTest  croppedImage = {this.getCroppedImg}/>

    getCroppedImg(img){

            alert("Perfect Storm");
            this.setState({

                previewImg:img

            })

        }

回答by RIYAJ KHAN

I think it is happening because in reactjs state changes are not occurring immediately. So how can i fix this?

我认为它正在发生,因为在 reactjs 状态更改不会立即发生。那么我该如何解决这个问题?

From the React#setState,

React#setState,

setState(updater, [callback])

设置状态(更新程序,[回调])

setState()enqueues changes to the component state. The setStatedoesn't immediately update the state. setState()does not always immediately update the component. It may batch or defer the update until later. This makes reading this.stateright after calling setState()a potential pitfall.Instead, use componentDidUpdateor a setStatecallback (setState(updater, callback))

setState()将更改加入组件状态。该setState不会立即更新状态。setState()并不总是立即更新组件。它可能会批量更新或推迟更新。这使得this.state在调用setState()潜在陷阱后立即阅读。相反,使用componentDidUpdatesetState回调(setState(updater, callback))

Call the this.props.croppedImagein the setStatecallback.You will get updated values of component state. In your case its this.state.preview

调用this.props.croppedImagesetStatecallback.You将得到更新组件的状态值。在你的情况下this.state.preview

this.setState({
  preview: {
    img,
    scale: this.state.scale,
  }
}, () => {
  this.props.croppedImage(this.state.preview.img);
})