【问题标题】:In react, I define a function but it's appear undefine在反应中,我定义了一个函数,但它似乎未定义
【发布时间】:2017-07-01 03:08:19
【问题描述】:

我定义了一个函数,但它在引用进程中没有定义。我试着加断点,结果显示是函数,但又继续执行错误,你是说form回调?

那是我引用的部分,提示requestServer不是函数,但是在下面的代码中已经定义了,不知道是不是回调的原因

import React, {Component, PropTypes} from 'react';
import GLogin from './Login';
var serverMethon = require('../../server/requestServer');
export default class LoginContainer extends Component {
    constructor(props) {
        super(props);
        this.state = {

        }
    }

    getLogin = (value) => {
        const {selectView} = this.props;
        const requestServer = serverMethon.requestServer;
        requestServer('login', value, function(t) {
            const data = JSON.parse(t.text);
            if (data.state != "successful") {
                alert("Login fail!")
                return;
            }
            selectView('SearchContainer');
        })();

    }
    render() {
        return (
        <GLogin 
        getLogin={this.getLogin}
        {...this.props}/>
      )
    }
}

函数定义部分

var superagent = require('superagent');

export const requestServer = (position, info, callback) => {
   superagent.post(`http://localhost:3000/${position}`)
   .send(info)
   .end((error, doc)=>{
       if(error){
        throw error
       }
       callback(doc)
   })
}

【问题讨论】:

  • 去掉})()的最后两个括号...

标签: node.js reactjs


【解决方案1】:
// proper way
 class App extends React.Component{
      constructor (props){
           super(props);  
           this.sampleMethod = this.sampleMethod.bind(this);
      }

      sampleMethod(){
            console.log('Sample method called');
      }

      render(){
           return <button onClick={this.sampleMethod}>Click Me</buttom>
      }
}

您的错误是您将方法称为 this.getLogin。但是您不绑定该方法。所以这个方法不能和this.getLogin一起使用。您可以使用 getLogin 方法而无需绑定。这次您通过 getLogin 调用了该方法,但是您在 getLogin 方法中获取了上下文,该上下文不是您的组件。当时你的上下文是窗口,所以你得到窗口对象。

所以首先绑定你的方法然后使用它。

// your mistake

getLogin = (value)=>{
    // your logic
}

// proper way

getLogin(value){
    // your logic
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2015-08-21
    • 2022-08-20
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    相关资源
    最近更新 更多