Home > Net >  Using function name as parameter of setState method?
Using function name as parameter of setState method?

Time:11-29

my question seems to be quite simple. But in the code below, how is it possible to use "prevState" as function without coding the function ?

handleAddOne() {
    this.setState(prevState => {
      return {
        counter: prevState.counter   1
      };
    });
  }

` Here you can see all the code in which handleAddOne() is include.

import React from "react";
import ReactDOM from "react-dom";

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    };
    this.handleAddOne = this.handleAddOne.bind(this);
  }
  handleAddOne() {
    this.setState(prevState => {
      return {
        counter: prevState.counter   1
      };
    });
  }
  render() {
    return (
      <div>
        <div>Counter: {this.state.counter}</div>
        <button onClick={this.handleAddOne}>Add One</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);

I didn't try anything special, just need explanation.

CodePudding user response:

How about using "React Hook" like "useState, useEffect()". it's can checked your value, and you can start function and setState also.

CodePudding user response:

I'm not sure if I understand your question properly because you DID code the function when you wrote:

prevState => {
  return {
    counter: prevState.counter   1
  };
}

This is an arrow function definition. You can store it in a variable and call it later or pass it as an argument to another function without storing it; as you did with this.setState. You can read more about js arrow functions here. Also, this is a recursive function that calls itself, and you can read about it here.

  • Related