对于这个 angularjs 代码,reactjs 中的等效代码是什么



我正在开发一个基于angularjs的网站。现在我想将一些片段转换为 reactjs,但我从未使用过 angularjs,所以显然我在理解用 angularjs 编写的代码时遇到了问题。我理解这里编写的一些代码,因为它用于保存帖子并在未保存时显示错误。但我不明白$scope以及如何转换这段代码来做出反应。我希望有人能帮助我

$scope.savepost=function(){
$scope.postdata={}
$scope.postdata['postTitle']=$scope.postTitle
$scope.postdata['postDescription']=$scope.postDescription
console.log($scope.postId)
if($scope.postId==null){
return $http.post('/api/saveposts',$scope.postdata).then(function(response){
if(response.status==200){
$scope.postId=response.data;
toaster.pop('success','post saved successfully!')                    
}else{                
toaster.pop('danger','An error has occured while saving the post. Please try again')                                        
}
});
}else{
$scope.postdata['postId']=$scope.postId        
return $http.post('/api/updateposts',$scope.postdata).then(function(response,status){
if(response.status==200){
toaster.pop('success','post saved successfully!')                                        
}else{
toaster.pop('danger','An error has occured while updating the post. Please try again')                                                            
}
});
}
}

它看起来像这样:

// destructure postId from props
const SomeFormComponent = ({ postId }) => {
const [postState, setPostState] = useState({title: '', description: ''})
/*
This example assumes you've set your input values to postState
*/
const handleRequest= async (url) => {
// copy all the input values set to state
const post = {...postState}
// this will be passed into fetch
const request = {
method: 'POST'
headers: {
'Content-Type': 'application/json'
}
}
if(postId != null) post['id'] = postId
try {
// use fetch, stringify json
const response = await fetch(url, { ...request, body: JSON.stringify(post )})
// handle json response
const data = await response.json()
if (data.status == 200) {
toaster.pop('success', 'post saved successfully!')
/*
Do something with the response
*/
} else {
toaster.pop('danger', 'An error has occurred while updating the post. Please try again')
}
} catch(ex) => {
console.error(ex.stack)
toaster.pop('danger', 'An error has occurred while updating the post. Please try again')
}
}

const handlePost = () => {
if(postId == null) {
return handleRequest('/api/savepost')
}
return handleRequest('/api/updatepost')
}
return (<button onClick={handlePost}>Save</button>)
}

最新更新