为什么在React js中第一次放大和缩小不起作用?

时间:2018-11-21 06:49:18

标签: javascript reactjs

能否请您告诉我为什么第一次放大和缩小按钮不起作用。当我第一次单击按钮时,放大和缩小按钮为什么不起作用?

这是我的代码 https://codesandbox.io/s/o4o98kwy0y

zoomIn = () => {
  console.log("zoom in");
  const { currentAngle, currentScale, zoomDelta } = this.state;
  const c = currentScale + zoomDelta;
  this.setState(state => ({
    ...state,
    currentScale: c
  }));
  this.drawImage();
};

zoomOut = () => {
  console.log("zoom in");
  const { currentAngle, currentScale, zoomDelta } = this.state;
  const c = currentScale - zoomDelta;
  this.setState(state => ({
    ...state,
    currentScale: c
  }));
  this.drawImage();
};

1 个答案:

答案 0 :(得分:0)

这是因为您正在设置状态并立即绘制图像,

您需要的是setState callback,这是一个示例

zoomOut = () => {
  console.log("zoom in");
  const { currentAngle, currentScale, zoomDelta } = this.state;
  const c = currentScale - zoomDelta;
  this.setState(state => ({
    ...state,
    currentScale: c
  }), () => {
    this.drawImage();
  });
};

Updated code in your link