【问题标题】:function works only in debbuger React函数仅在调试器 React 中有效
【发布时间】:2020-03-30 10:11:05
【问题描述】:

我是 React 的新手,所以我需要你的帮助。

我有一个包含多个输入的组件,所以我必须验证它们。

提交按钮默认是禁用的,只有当输入不为空时,我才能提交。

如果我删除输入中的值,按钮应该回到禁用状态。

我的问题是,这个函数(验证函数)只有在我一步步进行时才在调试器中工作

有人可以帮助我吗? 以下是我发现有助于理解我的问题的代码片段。

this.state = {
            profile: newProfile,
            disable: true,

        };



let newProfile= {
            firstName: "",
            lastName: "",
            nickname: "",
            email: ""
        };

 validate = () => {
        console.log(this.state)
        debugger;
        if (!this.state.profile.name || !this.state.profile.email) {
            return false;
        } else {
            console.log("Profile name and email NOT BLANK")
            console.log(this.state)
            return true;
        }
    };


profileChange= ((target, value) => {
            this.setState(prevState => {
                let profile= this.state.profile;
                profile[target] = value;
                    return {
                        profile: profile,

                    }

            })

 const isValid = this.validate();
        if (isValid) {
            console.log("valid inputs");
            this.setState({disable: false});
        }
        else{
            console.log("invalid inputs");
            this.setState({disable: true});
        }

    });

【问题讨论】:

    标签: javascript reactjs function validation


    【解决方案1】:

    setState 是一个异步函数 (Why?),在您调用 this.validate 时,this.state.profile 尚未设置。

    但是当您逐步执行执行时,状态正在更新为您想要的值,因此它对您有用。

    这里的解决方案是使用setState提供的callback函数,只有在设置状态后才执行验证。

    profileChange = (target, value) => {
      this.setState(prevState => {
        return {
          profile: {
            ...prevState.profile,
            [target]: value,
          }
        };
      }, () => {
        const isValid = this.validate();
        if (isValid) {
          console.log("valid inputs");
          this.setState({ disable: false });
        } else {
          console.log("invalid inputs");
          this.setState({ disable: true });
        }
      });
    };
    

    还请注意,我在setState 中使用了prevState 而不是this.state,因此profile 状态实际上并未发生突变。

    【讨论】:

      【解决方案2】:

      setState 函数是异步的,这意味着在更新状态时,可以触发其他函数。

      我认为在您的情况下发生的是状态正在更新,但在此之前,this.validate() 已经被调用。

      要解决此问题,您必须在更新该状态后添加要触发的代码,作为回调:

      this.setState(prevState => {
          let profile= this.state.profile;
          profile[target] = value;
      
          return {
              profile: profile,
          }
      }, () => {
          const isValid = this.validate();
      
          if (isValid) {
              console.log("valid inputs");
              this.setState({disable: false});
          } else {
              console.log("invalid inputs");
              this.setState({disable: true});
          }
      });
      

      【讨论】:

      • 乐于帮助@lagertha6!
      【解决方案3】:

      您可以在输入时使用“禁用”参数,这是一个示例

      class NameForm extends React.Component {
        constructor(props) {
          super(props);
          this.state = {value: ''};
      
          this.handleChange = this.handleChange.bind(this);
          this.handleSubmit = this.handleSubmit.bind(this);
        }
      
        handleChange(event) {
          this.setState({value: event.target.value});
        }
      
        handleSubmit(event) {
          alert('A name was submitted: ' + this.state.value);
          event.preventDefault();
        }
      
        render() {
          return (
            <form onSubmit={this.handleSubmit}>
              <label>
                Name:
                <input type="text" value={this.state.value} onChange={this.handleChange} />
              </label>
              <input type="submit" value="Submit" disabled={!this.state.value}/>
            </form>
          );
        }
      } 
      

      这是我为您制作的代码笔,用于更快地测试ragnar

      【讨论】:

        猜你喜欢
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 2018-11-10
        • 2017-01-30
        • 2019-08-22
        • 1970-01-01
        • 1970-01-01
        • 2015-01-14
        相关资源
        最近更新 更多