考虑我的代码示例(忘记密码表单)
import React, { PropTypes, Component } from 'react';
import $ from 'jquery';
import ManageCountry from '../ManageCountry';
import './style.css';
import {CONFIG} from '../const.js';
export default class Forgotpwd extends Component {
state = {
passwordText : "",
passwordTextConfirm : "",
expirated_reset_request: "none"
}
trad = {};
constructor () {
super();
ManageCountry.applyTradToState("single_sign_on", this.trad, () => {
var trad = this.trad.message.reset_password_form[0];
this.template = (
<div id="forgotpwd-form" role="form" >
<h3>{trad.form_title}</h3>
<p>{trad.form_desc}</p>
<div className="form-group">
<label htmlFor="emailfpwd">{trad.password_label}</label>
<input onChange={(password) => this.setState({passwordText:password.target.value})} type="email" id="emailfpwd" className="form-control" placeholder={trad.password_label}/>
</div>
<div className="form-group">
<label htmlFor="emailfpwd">{trad.password_confirmation_label}</label>
<input onChange={(password) => this.setState({passwordTextConfirm:password.target.value})} type="email" id="emailfpwd" className="form-control" placeholder={trad.password_label}/>
</div>
<p id="expirated_reset_request" style={{display : this.state.expirated_reset_request}}>{trad.expirated_reset_request}</p>
<div className="form-group">
<div className="row">
<div className="col-sm-6 col-sm-offset-3">
<button onClick={this.resetPwd.bind(this)} className="form-control btn btn-login">{trad.submit_label}</button>
</div>
</div>
</div>
</div>
);
});
}
resetPwd () {
var validate = this.validatePassword();
var token = window.location.href.split('=').pop();
console.log(token);
if(!token.match(new RegExp(/^[a-f\d.]+$/))) {
alert(this.trad.message.reset_password_form[0].bad_reset_request);
return false;
}
if(validate.success) {
$.post(CONFIG.APIURL+"user/forgotpwd/"+token, {password: this.state.passwordText}, (r) => {
if(r.success) {
window.location = "/"+ManageCountry.getUrlRoute()+"/login";
} else {
//$('#expirated_reset_request').css('display', 'block');
this.setState({expirated_reset_request : "block"});
console.log(this.state.expirated_reset_request);
//'block', but in HTML, the style is always 'none'
}
}, 'JSON');
}
}
validatePassword () {
if(this.state.passwordText != this.state.passwordTextConfirm) return {success : false, msg : "Les mots de passe ne correspondent pas"};
if(this.state.passwordText.length < 8) return {success : false, msg : "Le mot de passe doit faire 8 caractères au minimum"};
return {success : true};
}
render = () => {
return this.template;
}
}
我想更新一个带有表单错误的状态属性,这里是expirated_reset_request属性。
所以正如你所看到的,onClick执行resetPwd函数,在$ .post回调中,我正在更新状态以将显示从无(初始)更改为阻止。
之后的console.log告诉我,状态是最新的,但样式属性在HTML中永远不会改变(总是没有)
我忘记了什么吗?
提前致谢
答案 0 :(得分:1)
从我所看到的情况来看,this.template
变量只会填充一次。
然后,它永远不会改变。
要每次重新评估,请将其更改为函数:
this.template = () => (
<div ...
)