首页 文章

无法读取未定义的ReactJS属性'props'

提问于
浏览
1

我在ReactJS中收到错误“无法读取未定义的属性'道具'” . 我希望在登录后将页面路由到另一个页面,并传递会话的用户令牌,直到我的应用程序注销 . 我的代码:

...
    import { withRouter } from 'react-router';
    import { EventList } from "../EventList/EventList";

    export class SignIn extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          fields: {
            username: '',
            password: ''
          },
          errors: {}
        }
        this.onSubmit = this.onSubmit.bind(this);
      }
      ...
      onSubmit(e){
        e.preventDefault();
        if(this.handleValidation()){
          var apiBaseUrl = "http://api.eventsacross-stage.railsfactory.com/api/";
          var input = this.state.fields;
          axios.post(apiBaseUrl+'v1/users/signin', input)
          .then(function (response) {
             console.log(response);
             if(response.data.status == 200){
               console.log("Login successful");
               alert("Login successful");
               this.props.router.push('/EventList');
             }
             else if(...
             }
           })...
           });
         }
      }
    ...
      render() {
        return (
          ...
          <button type="submit" className="btn btn-primary btn-lg pull-right" onClick={this.onSubmit}>Sign In</button>
...
        );
      }
    }

    export default withRouter(SignIn);

3 回答

  • 1

    正如@astorga所指出的,你对'this'有错误的背景 . 但我建议使用Arrow Function而不是存储'that'变量 .

    onSubmit(e) {
        e.preventDefault();
        if(this.handleValidation()){
            var apiBaseUrl = "http://api.eventsacross-stage.railsfactory.com/api/";
            var input = this.state.fields;
            axios.post(apiBaseUrl+'v1/users/signin', input)
              .then((response) => { // Arrow function here, which doesn't create new 'this' scope
                 if(response.data.status == 200) {
                   this.props.router.push('/EventList');
                 }
                 else if(...
                 }
              });
           }
        }
    }
    
  • 1

    this 里面 then 函数的值与 onSubmitonSubmit 函数不同 . 您可以在此处阅读有关 this 行为的更多信息:this|MDN

    为了实现这一点,你应该将正确的 this 值存储在另一个变量中,就像@ thomas-lin所说:

    onSubmit(e){
      var that = this;
      // ...
      // later, on axios call:
      axios.post(apiBaseUrl+'v1/users/signin', input)
      .then(function (response) {
        console.log(response);
        if(response.data.status == 200){
          console.log("Login successful");
          alert("Login successful");
          that.props.router.push('/EventList');
        }
        else if(...) {
          //...
        }
      })
    
  • 3

    错误地使用“this”导致了这个错误,尝试这样的代码:

    onSubmit(e){
      var that = this
      .....
      that.props.router.push('/EventList');
    
    }
    

相关问题