简体   繁体   English

SetState导致React.js中的应用程序崩溃

[英]SetState causing App crash in react.js

I have recently started working on react.js , while creating the login page I have used setstate method to set the value of userEmail to text box. 我最近开始上react.js工作,同时创造我已经使用了登录页面setstate方法来设置的值userEmail到文本框。

I have created a method which checks the validity of email address and I am calling it every time when user enters a new letter. 我创建了一种检查电子邮件地址有效性的方法,每次用户输入新字母时都会调用它。

handleChangeInEmail(event) {
    var value = event.target.value;
    console.log("change in email value" + value);
    if(validateEmailAddress(value) == true) {
      this.setState(function() {
        return {
              showInvalidEmailError : false,
              userEmailForLogin: value,
           }
     });
   } else {
     this.setState(function() {
       return {
              showInvalidEmailError : true,
              userEmailForLogin: value

      }
  });
}

This method and userEmailForLogin state is passed in render method as 此方法和userEmailForLogin staterender方法中传递为

<EmailLoginPage  
   userEmailForLogin = {this.state.userEmailForLogin}
   onHandleChangeInEmail= {this.handleChangeInEmail}
/>

I am using the method to validate the email address and the method is 我正在使用该方法来验证电子邮件地址,并且该方法是

validateEmailAddress : function(emailForLogin) {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailForLogin))  {  
            return true; 
        }  
        return false;  
    },

I am using this method and state in render of EmailLoginPage as <input type="text" name="" placeholder="Enter Email" className="email-input-txt" onChange={props.onHandleChangeInEmail} value = {props.userEmailForLogin}/> 我用这个方法和状态呈现EmailLoginPage<input type="text" name="" placeholder="Enter Email" className="email-input-txt" onChange={props.onHandleChangeInEmail} value = {props.userEmailForLogin}/>

This is working fine in normal case , but when I try to input a large email addess say yjgykgkykhhkuhkjhgkghjkhgkjhghjkghjghghkghbghbg@gmail.com , it crashes 在正常情况下,此方法工作正常,但是当我尝试输入大型电子邮件地址时,说yjgykgkykhhkuhkjhgkghjkhgkjhghjkghjghghkghbghbg@gmail.com ,它崩溃了

IMO the frequent change in state is causing this but I couldn't understand what should be done to get rid of this. IMO频繁的状态变化导致了这种情况,但是我不知道该怎么做才能摆脱这种情况。

A solution using debounce. 使用去抖动的解决方案。 This way multiple setState can be reduced. 这样可以减少多个setState。

DEMO: https://jsfiddle.net/vedp/kp04015o/6/ 演示: https : //jsfiddle.net/vedp/kp04015o/6/

class Email extends React.Component {
    constructor (props) {
        super(props)
        this.state = { email: "" }
    }

    handleChange = debounce((e) => {
        this.setState({ email: e.target.value })
    }, 1000)

    render() {
        return (
            <div className="widget">
                <p>{this.state.email}</p>
                <input onChange={this.handleChange} />
            </div>
        )
    }
}

React.render(<Email/>, document.getElementById('container'));


function debounce(callback, wait, context = this) {
  let timeout = null 
  let callbackArgs = null

  const later = () => callback.apply(context, callbackArgs)

  return function() {
    callbackArgs = arguments
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

I think issue is with the regex only, i tried with other and it's working properly. 我认为问题仅在于regex ,我尝试了其他regex ,并且工作正常。

Instead of writing the if/else inside change function simply you are write it like this: 您无需像编写if/else内部change函数那样编写它:

change(event) {
    var value = event.target.value;
    this.setState({
       showInvalidEmailError : this.validateEmailAddress(value),
       value: value,
    });
}

Copied the regex from this answer: How to validate email address in JavaScript? 从以下答案中复制了regex如何在JavaScript中验证电子邮件地址?

Check the working solution: 检查工作解决方案:

 class App extends React.Component { constructor(){ super(); this.state = { value: '', showInvalidEmailError: false } this.change = this.change.bind(this); } change(event) { var value = event.target.value; this.setState(function() { return { showInvalidEmailError : this.validateEmailAddress(value), value: value, } }); } validateEmailAddress(emailForLogin) { var regex = /^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/; if(regex.test(emailForLogin)){ return true; } return false; } render() { return( <div> <input value={this.state.value} onChange={this.change}/> <br/> valid email: {this.state.showInvalidEmailError + ''} </div> ); } } ReactDOM.render( <App/>, document.getElementById("app") ); 
 <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='app'/> 

You could use Lodash's debounce function so that the check function is not called unless the user stops typing for x amount of time (300ms in my scenario below). 您可以使用Lodash的反跳功能,以便除非用户停止键入x的时间量(在下面的情况下为300ms),否则不调用check函数。

_this.debounceCheck = debounce((value) => {
  if(validateEmailAddress(value)) {
    this.setState(function() {
      return {
        showInvalidEmailError : false,
        userEmailForLogin: value,
      }
    });
  } else {
    this.setState(function() {
      return {
        showInvalidEmailError : true,
        userEmailForLogin: value
      }
    });
  }
}, 300)

handleChangeInEmail(event) {
  _this.debounce(event.target.value)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM