(this)在反应js回调中被识别

时间:2017-05-17 11:18:16

标签: javascript reactjs react-redux babeljs

    class App extends Component {
      constructor(props){
        super(props);

         this.state = {
           histories: [
                {
                 "name": "Test1",
                 "date":"25/05/2017",
                 "question": "Are you happy, today?",
                 "answer":"Yes"
                }, 
                {
                 "name": "Test2",
                 "date":"25/05/2017",
                 "question": "Are you happy, today?",
                 "answer": "Yes"
                }
              ] }; 

               $.ajax({
          url: "http://localhost:xxxx/api/Surveys",
          success: (data) => {
              this.setState({surveys: data});
            },
            error: function(xhr,status,err){
              console.log('error');
            }
        });
        }

         onFormSubmit(id) {
        console.log("Started");
        fetch("http://localhost:xxxx/api/Surveys/" + id + "/submit", {
            method:'POST'
        })
        .then(function(response){
          if(response.ok) {
            console.log('success');
            //this is not defined here
             this.setState({
               histories: [
                {
                 "name": "Test3",
                 "date":"25/05/2017",
                 "question": "Are you happy, today?",
                 "answer":"Yes"
                }, 
                {
                 "name": "Test4",
                 "date":"25/05/2017",
                 "question": "Are you happy, today?",
                 "answer": "Yes"
                }
              ]
          })
          }
          else {
            console.log('error');
          }
        })
        .catch(function(error){
          console.log('catch error');
        });
      }
 render(){
    return ( 
      <div>
          <History 
           Histories={this.state.histories} />
      </div>
    );
  }
      }

嗨,我是新手做出反应,我已经在构造函数中声明了历史记录,我试图在回调时在webservice中设置历史状态,这在调试时是未定义的。 这是在<History Histories={this.state.histories} />中定义的,但它在回调中是未定义的,请问有人帮我吗?我搜索过,有些人建议使用ref,但是如何才能将ref连接到这个状态呢?如果有人举一个例子,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

您尝试在onFormSubmit函数中设置“历史记录”。要访问组件的“this”,需要将其绑定到函数,即

onFormSubmit {
.... 
}.bind(this)

或在构造函数

this.onFormSubmit = this.onFormSubmit.bind(this)

答案 1 :(得分:0)

你应该在onFormSubmit方法中传递箭头函数作为AJAX调用的成功回调,以确保此回调中的this指向组件:

onFormSubmit(id) {
        console.log("Started");
        fetch("http://localhost:xxxx/api/Surveys/" + id + "/submit", {
            method:'POST'
        })
        .then((response) => {
             ...
        })

}