gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:50:04 25 4
gpt4 key购买 nike

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

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

关于javascript - 对于这个 angularjs 代码,reactjs 中的等效代码是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58219061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com