简体   繁体   English

如何正确地将代码从 angularjs 迁移到 reactjs

[英]How to correctly migrate the code from angularjs to reactjs

I'm trying to migrate the code from angular to react.我正在尝试从 angular 迁移代码以做出反应。 Not sure if it's correct, just need some help if I'm going in the right direction or not.不确定它是否正确,如果我朝着正确的方向前进,只需要一些帮助。 I don't know angular so I'm having confusion if the 'textdata' is something like a state in react and will I have to declare it in states at the top or not我不知道 angular 所以我很困惑,如果“textdata”在反应中类似于 state,我是否必须在顶部的状态中声明它

The angular code angular代码

 $scope.textanalysis=function(){
  return $http.post('/api/analyse',{'snippetdesc': snippetDescription}).then(function(response){
      if(response.status==200){
          textdata=response.data
          textlen=snippetDescription.split(' ').length
      }else{
          console.log('danger','An error has occured while updating the snippet. Please try again');
      }
  })
}

The one which I translated to react我翻译的那个反应

componentDidMount() {
textanalysis(){  
fetch('/api/analyse', {
    method: 'POST',
    body: JSON.stringify({
      snippetdesc: 'snippetDescription'
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8"
    }
  }).then(response => {
      return response.json()
    }).then(textdata => {
      this.setState({
        textdata = response.data
        textlen=snippetDescription.split(' ').length
      });
    });
}

Try this, Hope it will work.试试这个,希望它会工作。

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      textdata: [],
      textlen: 0
    };
  }

textanalysis(){  
fetch('/api/analyse', {
    method: 'POST',
    body: JSON.stringify({
      snippetdesc: 'snippetDescription'
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8"
    }
  })
  .then(response =>  response.json())
  .then((textdata) => {
      this.setState({
        textdata : textdata.data,
        textlen : snippetDescription.split(' ').length
      });
    },(error) => {
          console.log(error)
    })
}  
}

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

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