reactJS <select>不更新状态

时间:2019-03-27 17:26:56

标签: javascript reactjs

我有一个reactJS应用程序,在其中提示用户输入一些信息。这是要求用户从值= {currentComponent.state.securityQuestion} onChange = {(事件)=> this.saveQuestion(事件)}>                                                                                          
    
    
        
                     
    
    
        
             this.saveAnswer(event)} />          
    
我的状态如下所示:     this.state = {         passData:this.props.location.state,         planID:“”,         会员ID: ””,         PIN:“”,         用户身份: ””,         密码:“”,         安全问题: ””,         securityAnswer:“”,         电子邮件:“”      } 我也有以下内容: saveQuestion(event){     让currentComponent = this;     var localQuestion = event.target.value;     console.log(“ localQuestion:”,localQuestion);     currentComponent.setState({securityQuestion:localQuestion});  } 和 saveAnswer(事件){     让currentComponent = this;     var localAnswer = event.target.value;     currentComponent.setState({securityAnswer:localAnswer}); } 当我执行该应用程序并滚动或单击选择选项时,我的控制台中从未显示任何内容。在此过程的最后,我用所选值和输入的文本字符串构建一个字符串。要进行测试,我在输入框中输入“测试字符串”,然后选择了第一个选择选项。我本来希望在生成的字符串中看到值“ 0test字符串”,但会得到“测试字符串”,证明状态变量未通过附加到select的onChange进行更新。 有什么建议么?

3 个答案:

答案 0 :(得分:5)

您选择的代码中有错字:

<select className="text_15"> value={currentComponent.state.securityQuestion} onChange={(event) => this.saveQuestion(event)}>
    <option value="0">What is you mother's maiden name?</option>
    <option value="1">What elementary school did you attend?</option>
    <option value="2">What was the name of your first pet?</option>
    <option value="3">What city were you born in?</option>
</select>

应该是:

<select className="text_15" value={currentComponent.state.securityQuestion} onChange={(event) => this.saveQuestion(event)}>
    <option value="0">What is you mother's maiden name?</option>
    <option value="1">What elementary school did you attend?</option>
    <option value="2">What was the name of your first pet?</option>
    <option value="3">What city were you born in?</option>
</select>

您的select标签上还有一个>

答案 1 :(得分:1)

您设置状态的方式正在丢失您以前的状态信息。

currentComponent.setState({ ...this.state,securityAnswer:localAnswer });

...this.state被称为扩展,将保留您不想更改的状态元素。

答案 2 :(得分:0)

将函数绑定到this,或使用箭头函数语法:

saveQuestion = (event) => {    
  let currentComponent = this;  
  var localQuestion = event.target.value;
  console.log("localQuestion: ", localQuestion);
  this.setState({securityQuestion: localQuestion});
}
相关问题
最新问题