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



我正在尝试将代码从角度迁移到反应。不确定它是否正确,如果我朝着正确的方向前进,只需要一些帮助。我不知道角度,所以我很困惑"textdata"是否类似于反应状态,我是否必须在顶部的状态中声明它

角度代码

$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');
}
})
}

我翻译的那个反应

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
});
});
}

试试这个,希望它会起作用。

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)
})
}  
}

最新更新