I'm trying to migrate the code from angular to react. 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
The angular code
$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)
})
}
}
来源:https://stackoverflow.com/questions/58298526/how-to-correctly-migrate-the-code-from-angularjs-to-reactjs