【问题标题】:What would be the equivalent code in reactjs for this angularjs code对于这个 angularjs 代码,reactjs 中的等效代码是什么
【发布时间】:2026-02-03 12:25:01
【问题描述】:

我正在开发一个基于 angularjs 的网站。现在我想将几个 sn-ps 转换为 reactjs 并且我从未使用过 angular,所以很明显我在理解用 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')                                                            
            }
        });
    }
}

【问题讨论】:

  • 你好 UbuntuNewb!欢迎来到堆栈溢出。视线的重点是创建一个知识库,没有任何“调试/编写我的代码”问题。鉴于此,您能否具体告诉我们您的问题是什么,以及您尝试了什么?
  • 有这个网站是用 angularjs 编写的。上面的代码是我从 wesbite 中提取的一段简单的代码,它基本上是为了保存帖子而编写的。阅读帖子后,我可以理解代码在做什么,但我无法理解所有这些语法的含义,所以我想要上面这段代码的等效代码

标签: javascript reactjs


【解决方案1】:

看起来像这样:

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

【讨论】:

  • 我认为如果 postId==null,那么它不会删除 post.id,但它会分配一个新的 post.id,如果它已经存在,那么它将使用该帖子更新现有帖子.id,对吧?
  • 您是否从您的回复中获得了 postId?如果是这样,您应该只担心在 PUT'ing 或 PATCh'ing 时提交带有请求的 postId。您的数据库应在创建记录时生成一个 ID。
  • 你根本没有调用 api /savepost 。我认为当没有 id 匹配它时应该首先调用它。如果 id 存在,那么我们应该调用 api/updatepost,不是吗?