状态不更新React中的组件

时间:2018-02-13 06:36:48

标签: reactjs

我试图创建一个tapper组件,每当用户点击按钮时,组件内部的数字就会增加一个。

enter image description here

tapper组件从本地json文件获取初始值。当按下敲击器时,它会触发onClick功能,但不会更新状态,因此数字不会上升!我有新的反应,所以我不知道我是否错误地解决了这个问题。

我将来的目的是让按钮更新json值,以便将来访问该页面的任何人都可以点击它并使数字上升。

import React, {Component} from 'react';
import {Icon, Label} from 'semantic-ui-react';
import tapperValue from './tappervalue.json';

    export default class TapperOutput extends Component {

      constructor() {
        super();

        this.state = {
          tapperValue: tapperValue.tapperValue
        }
      }

      handleClick = () => {
        console.log('Before the conversion ' + this.state.tapperValue);
        const taps = this.state.tapperValue + 1;
        this.setState = ({tapperValue: taps});
        console.log('After the conversion ' + this.state.tapperValue);
      }

      render() {

        return (
        <Label onClick={this.handleClick}>
          <Icon name='hand paper'/> {this.state.tapperValue}
        </Label>);
      }
    }

1 个答案:

答案 0 :(得分:4)

首先,setState是一个函数,你不需要赋值赋值运算符。

第二: setStateasync,因此更新不会立即可见,因此您需要在setState回调中记录该值。查看this answer了解详情

第三:当您根据前一个状态更新当前状态时,最好使用setState提供的更新程序函数语法。在when to use Updater function with setState

上查看此答案

简单写一下

  handleClick = () => {
    console.log('Before the conversion ' + this.state.tapperValue);
    this.setState(prevState => ({tapperValue: prevState.tapperValue + 1}), () => {
        console.log('After the conversion ' + this.state.tapperValue);
    });

  }
相关问题