Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

javascript - init state without constructor in react

import React, { Component } from 'react';

class Counter extends Component {
  state = { value: 0 };

  increment = () => {
    this.setState(prevState => ({
      value: prevState.value + 1
    }));
  };

  decrement = () => {
    this.setState(prevState => ({
      value: prevState.value - 1
    }));
  };

  render() {
    return (
      <div>
        {this.state.value}
        <button onClick={this.increment}>+</button>
        <button onClick={this.decrement}>-</button>
      </div>
    )
  }
}

Usually what I saw is people do this.state within the constructor function if he used es6 class. If he isn't he probably put the state using getinitialstate function. But above code (yes it's a working code), did not used either both. I have 2 question, what is state here? is that a local variable? if yes why it has no const? where does the prevState come from? why arrow function is used in setState? isn't it's easy to just do this.setState({value:'something'})?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have 2 question, what is state here?

An instance property, like setting this.state = {value: 0}; in a constructor. It's using the Public Class Fields proposal currently at Stage 2. (So are increment and decrement, which are instance fields whose values are arrow functions so they close over this.)

is that a local variable?

No.

where does the prevState come from? why arrow function is used in setState? isn't it's easy to just do this.setState({value:'something'})?

From the documentation:

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

For example, this code may fail to update the counter:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

...which is exactly what the quoted code is doing. This would be wrong:

// Wrong
increment = () => {
  this.setState({
    value: this.state.value + 1
  });
};

...because it's relying on the state of this.state, which the above tells us not to; so the quoted code does this instead:

increment = () => {
  this.setState(prevState => ({
    value: prevState.value + 1
  }));
};

Here's proof that React may batch calls in a non-obvious way and why we need to use the callback version of setState: Here, we have increment and decrement being called twice per click rather than once (once by the button, once by a span containing the button). Clicking + once should increase the counter to 2, because increment is called twice. But because we haven't used the function callback version of setState, it doesn't: One of those calls to increment becomes a no-op because we're using a stale this.state.value value:

class Counter extends React.Component {
  state = { value: 0 };

  increment = () => {
    /*
    this.setState(prevState => ({
      value: prevState.value + 1
    }));
    */
    console.log("increment called, this.state.value = " + this.state.value);
    this.setState({
      value: this.state.value + 1
    });
  };
  
  fooup = () => {
    this.increment();
  };

  decrement = () => {
    /*
    this.setState(prevState => ({
      value: prevState.value - 1
    }));
    */
    console.log("decrement called, this.state.value = " + this.state.value);
    this.setState({
      value: this.state.value - 1
    });
  };
  
  foodown = () => {
    this.decrement();
  };

  render() {
    return (
      <div>
        {this.state.value}
        <span onClick={this.fooup}>
          <button onClick={this.increment}>+</button>
        </span>
        <span onClick={this.foodown}>
          <button onClick={this.decrement}>-</button>
        </span>
      </div>
    )
  }
}

ReactDOM.render(
  <Counter />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...