简体   繁体   English

简单的 JS vanilla/react function 重写,但是如何?

[英]Simple JS vanilla/react function rewrite, but how?

I have a written a nasty bit of code over and over, but how can I make it a reusable function (and how would I call it?) step: step - 'x' <--- this is the only functional bit that actual changes!我一遍又一遍地写了一段讨厌的代码,但是我怎样才能使它成为可重用的 function (我怎么称呼它?) step: step - 'x' <--- 这是唯一实际的功能位变化!

This is the nasty code:(这是讨厌的代码:(

  prevStep2 = () => {
    const { step } = this.state;
    this.setState({
      step: step - 6
    });
    window.scrollTo(0, 0);
  };
  //Back to step 3
  prevStep3 = () => {
    const { step } = this.state;
    this.setState({
      step: step - 5
    });
    window.scrollTo(0, 0);
  };
  //Back to step 4
  prevStep4 = () => {
    const { step } = this.state;
    this.setState({
      step: step - 4
    });
    window.scrollTo(0, 0);
  };
  //Back to step 5
  prevStep5 = () => {
    const { step } = this.state;
    this.setState({
      step: step - 3
    });
    window.scrollTo(0, 0);
  };
  //Back to step 6
  prevStep6 = () => {
    const { step } = this.state;
    this.setState({
      step: step - 2
    });
    window.scrollTo(0, 0);
  };
  //Back to step 7
  prevStep7 = () => {
    const { step } = this.state;
    this.setState({
      step: step - 1
    });
    window.scrollTo(0, 0);
  };

My attempt at the rewrite:我的重写尝试:

function backToStep(stepNumber){
    const { step } = this.state;
    this.setState({
      step: step - stepNumber
    });
    window.scrollTo(0, 0);
}

Called like称为

<button onClick={this.backToStep(5)}>Test</button>

But not sure if it would work properly!但不确定它是否能正常工作!

onClick expects a function. onClick需要一个 function。 this.backToStep(5) returns void , so you have a problem. this.backToStep(5)返回void ,所以你有问题。 You need either to pass an anonymous function to onClick :您需要将匿名 function 传递给onClick

<button onClick={() => this.backToStep(5)}>Test</button>

Or to make backToStep return a function:或者让backToStep返回一个 function:

function backToStep(stepNumber) {
  return () => {
    const { step } = this.state;
    this.setState({
      step: step - stepNumber
    });
    window.scrollTo(0, 0);
  }
}

<button onClick={this.backToStep(5)}>Test</button>

Also, it's considered a good practice to use the callback parameter when your setState depends on the actual state.此外,当您的setState取决于实际的 state 时,使用回调参数被认为是一种很好的做法

If the next state depends on the current state, we recommend using the updater function form, instead:如果下一个 state 依赖于当前 state,我们建议使用更新程序 function 形式,而不是:

this.setState(prevState => ({
  step: prevState.step - stepNumber
}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM