如果不使用箭头符号,你会怎么写?

时间:2018-03-21 18:49:43

标签: javascript arrow-functions

在我的increaseCount方法中,我有3种不同的增加计数的方法。我认为第一种方法可以使用两次但它不起作用,因为它似乎在回调中合并了setState。使用回调函数的正确方法是什么?为什么箭头符号有效? prevState.count是如何定义的?永远不会设置为0

import React from "react";
import { render } from "react-dom";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center"
};

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  increaseCount() {
    console.log(this);
    this.setState({ count: this.state.count }, function() {
      this.setState({ count: this.state.count + 1 });
    });

    this.setState({ count: this.state.count + 1 });

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

  render() {
    return (
      <div style={styles}>
        <div>
          <button onClick={() => this.increaseCount()}>Increase</button>
        </div>
        <h2>{this.state.count}</h2>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

this.setState(prevState=>({count: prevState.count + 1}))

2 个答案:

答案 0 :(得分:2)

this.setState(function(prevState) {
  return {count: prevState.count + 1};
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

答案 1 :(得分:1)

this.setState(function (prevState) {
  return {count: prevState.count + 1};
});
  

https://reactjs.org/docs/react-component.html#setstate

https://codepen.io/anon/pen/BrRzgB?editors=1011

updater函数接收的prevState和props都保证是最新的。 updater的输出与prevState轻微合并。

  

setState(updater [,callback])