如何在React JS中处理this.setState问题

时间:2018-12-09 16:18:21

标签: javascript reactjs react-native bootstrap-4 reactstrap

由于某些原因,当我按下下一步按钮时,setState的值未更新。它用于进度条,每按一次该按钮,进度条加20。就像value:this.state.value + 20一样,有人知道发生了什么吗?任何帮助表示赞赏。谢谢!

    {% for key, value in allforms.items %}
     {% for field in value %}
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10"> <!--this gonna be only displayed if there is an error in it-->
                <span class="text-danger small">{{ field.errors }}</span>
            </div>
            <label class="control-label col-sm-2">{{ field.label_tag }}</label>
            <div class="col-sm-10"> <!--this gonna be displayed if there is no error -->
                {{ field }}
            </div>
        </div>
   {% endfor %}
{% endfor %}

3 个答案:

答案 0 :(得分:0)

在render函数内部更改状态是错误的。在每次更新时,状态都会改变。状态在反应中是一成不变的。您可以在构造函数中对其进行初始化。

  constructor(props) {
        super(props);
        this.state = {

            value:10
             }
       }

答案 1 :(得分:0)

您应该使用构造函数来初始化值。当您单击按钮时,代码正在更新值,但是setState重新渲染了它,所以它又在初始化值= 10。

import React, {Component} from "react";
import { Button, Progress } from 'reactstrap';
import "../src/Questions.css"

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


 handleClick=()=>{
     alert(this.state.value);
     this.setState({
         value:this.state.value +20
     })


 }

render() {

    return(
        <div>
            <div><Progress value={this.state.value} /></div>
            <div className="howMuchText">How much does it cost to build an app</div>


            <div className="nextButton">
            <Button onClick={this.handleClick} color="primary" size="lg">Next</Button>
            </div>
        </div>
    )
 }
}

  export default Questions;

答案 2 :(得分:0)

之所以不进行更新,是因为您正在使用setState函数中的handleClick更新状态,然后在render函数中将其重置,因此您要撤消更新。尝试这个。

从您的来源更改为此:

import React, { Component } from "react";
import { Button, Progress } from 'reactstrap';
import "../src/Questions.css"

//you've imported component so you don't need to do React.Component
class Questions extends Component {

   state = { 
     value: 10, 
   } 
     handleClick = () =>{
         alert(this.state.value);
         this.setState({
             value: this.state.value +20
         })
     }

    render() {

        return(
            <div>
                <div><Progress value={this.state.value} /></div>
                <div className="howMuchText">How much does it cost to build an app</div>


                <div className="nextButton">
                <Button onClick={this.handleClick} color="primary" size="lg">Next</Button>
                </div>
            </div>
        )
    }
}

这应该做到。希望这会有所帮助。