使用React将状态值递增1

时间:2017-02-21 10:32:11

标签: reactjs state

在React中我试图使按钮增加存储在状态中的值。 但是,使用下面的代码函数时,我的值在使用handleClick时设置为undefined或NaN。

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

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

   handleClick = (prevState) => {
    this.setState({value: prevState.value + 1});
    console.log(this.state.value)
  }

你能告诉我为什么会这样吗?根据这里的文档,它应该是正确的: https://facebook.github.io/react/docs/state-and-lifecycle.html

9 个答案:

答案 0 :(得分:16)

因为您错误地使用了handleClick函数。这里:

handleClick = (prevState) => { .... }

prevState将是一个传递给handleClick函数的事件对象,你需要使用带有setState的prevState,如下所示:

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

另一个问题是,setState是异步的,因此console.log(this.state.value)不会打印更新的状态值,你需要使用setState的回调函数。

查看有关async behaviour of setState的详细信息以及如何检查更新后的值。

检查工作解决方案:



class App extends React.Component {
 
   constructor(props){
       super(props);
       this.state={ count: 1}
   }
 
  onclick(type){
      this.setState(prevState => {
         return {count: type == 'add' ? prevState.count + 1: prevState.count - 1}
      });
  }

   render() {
    return (
      <div>
        Count: {this.state.count}
        <br/>
        <div style={{marginTop: '100px'}}/>
        <input type='button' onClick={this.onclick.bind(this, 'add')} value='Inc'/>
        <input type='button' onClick={this.onclick.bind(this, 'sub')} value='Dec'/>
       </div>
     )
   }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);
&#13;
<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>

<div id='container'></div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

set state是async,因此当console.log发生时你不会看到值更新。您应该在UI上打印状态值,这样您就可以看到发生了什么。要修复控制台日志,请尝试此操作。

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

   handleClick = (prevState) => {
    this.setState({value: prevState.value + 1}, () => {
        console.log(this.state.value)
    });
  }

注意:为反应类this定义内联lambda(箭头函数)时,绑定正确,因此您不需要在构造函数中绑定它。

如果它只是像这样的状态增量

,你也可以改变传递前一个数字的方式
handleClick = () => {
    this.setState({value: this.state.value + 1}, () => {
        console.log(this.state.value)
    });
}

答案 2 :(得分:2)

class SkuVariantList extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        clicks: 0
      };
      this.clickHandler = this.clickHandler.bind(this)
    }

    componentDidMount() {
      this.refs.myComponentDiv.addEventListener('click', this.clickHandler);
    }

    componentWillUnmount() {
      //this.refs.myComponentDiv.removeEventListener('click', this.clickHandler);
    }

    clickHandler() {
      var clk = this.state.clicks
      this.setState({
        clicks: clk + 1
      });
    }

    render() {
      let children = this.props.children;

      return (
        <div className="my-component" ref="myComponentDiv">
          <h2>My Component ({this.state.clicks} clicks})</h2>
          <h3>{this.props.headerText}</h3>
          {children}
        </div>
      );
    }
  }

答案 3 :(得分:2)

您好,请尝试使用这些代码来增加您的值

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

addOne() {                              // addOne as HandleClick
  this.setState((preState) => {
    return {
      count : preState.count + 1
      };
   });
 }

render() {
   return (
      <div>
        <h1>Count : {this.state.count}</h1>
        <button onClick={this.addOne}>+1</button>
      </div>
     );
   }
 }

ReactDOM.render(<Counter />, document.getElementById('YOUR-ID'));

答案 4 :(得分:1)

试试这个

public void addEvent(VEvent event, VTimeZone timezone){
                    try {
                        Calendar calendar = new Calendar();
                        calendar.getProperties().add(new ProdId(prodId));
                        calendar.getProperties().add(Version.VERSION_2_0);
                        calendar.getProperties().add(CalScale.GREGORIAN);
                        calendar.getComponents().add(event);
                        collection.add(httpClient, calendar);
                    } catch (CalDAV4JException e) {
                        e.printStackTrace();
                    }

    }

请注意,当您设置状态时,它会触发渲染功能,该功能将反映当前状态。在浏览器中试试吧!

答案 5 :(得分:1)

class CounterApp extends React.Component {
  constructor() {
    super();
    //here count is initially assigned with 0
    this.state = {
      count: 0,
    };
  }

  //when we click Increment or Decrement +1 or -1 is passed to step and the value gets changed it gets updated to the view
  increment = (step) => {
    this.setState({
      count: this.state.count + step,
    });
  };

  render() {
    const { count } = this.state; //same as const count = this.state.count;

    return (
      <div>
        <div className="counter-app">
          <h2 className="value">{count}</h2>
          <button onClick={() => this.increment(+1)}>Increment</button>
          <button onClick={() => this.increment(-1)}>Decrement</button>
        </div>
      </div>
    );
  }
}

答案 6 :(得分:0)

driver.get("https://sales.aig.co.il/travel")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'chkDestination-title156')))
elm156 = driver.find_element_by_id("chkDestination-title156")
elm156.click()

答案 7 :(得分:0)

这是最短的代码。首先,初始化状态,然后执行增加方法。

state = {
    counter: 0
  }
increaseHandler = () => {
    let counter = this.state.counter
    counter += 1
    this.setState({counter: counter})
  }

答案 8 :(得分:0)

您也可以通过相同的功能进行增量和减量运算,从而使其更加模块化和可重现

class CounterApp extends React.Component{

    constructor(){
        super();
        //here count is initially assigned with 0
        this.state ={
        count:0
        }
    }
    
    //when we click Increment or Decrement +1 or -1 is passed to step and the value gets changed it gets updated to the view
    increment = (step) =>{
        this.setState({
            count:this.state.count + step
        })
    }
    render(){
        const { count } = this.state;//same as const count = this.state.count;

        return(
            <div>
                <div className="counter-app">
                    <h2 className="value">{count}</h2>
                    <button onClick={() => this.increment(+1)}>Increment</button>
                    <button onClick={() => this.increment(-1)}>Decrement</button>
                </div>
            </div>
        )
    }
}