【问题标题】:My comments for my comment section isn't showing up我的评论部分的评论没有显示
【发布时间】:2021-01-22 05:31:52
【问题描述】:

我正在为我的网站创建一个评论部分,在我的前端,我想创建一个函数来显示用户在数据库中发布的评论。

但是当我创建了一个检索评论并显示它的函数时,评论不会显示出来。我不知道我做错了什么,是我放错了地方还是我编程正确?

这是我的后端程序

app.post('/forum', function (req, res){
  const queryString = "INSERT INTO comments (Comments) VALUES (?)"
  console.log (req.body)
  con.query(queryString, [req.body.comment], function (err, result){
    if (err) {
      throw err;
    }
    if (result.length != 1) {
      return res.send("Posted Comment")
    }
   else {
     res.send('Comment failed to post')
    };
    })
})

app.get('/forum', function (req, res){
  const queryString = 'SELECT * FROM comments WHERE Comments = ?'
  console.log (req.body)
  con.query(queryString, [req.body.insert], function (err, result){
    if (err) {throw err;}
    var commenting = JSON.stringify(result)
    res.send(commenting);    
  }) 
})

获取响应的 api 调用

 static async forum(comm){        
      const response = await axios
       .post('http://localhost:8080/forum', {
          comment: comm,
       })    
       .then ()
          return response.data;
           
        
    }

 static async comment(comm){    
        const response = await axios    
          .get('http://localhost:8080/forum', {
             comment: comm
            }) 
          .then ()
            return response.data;   
    }

还有我的前端会显示评论

function Forum() {
    
    const [comment, inputComment] = useState ('')
    
    /*user posts the comment*/
    const onPost = (event) => {  
    event.preventDefault()
    apiClient.forum(comment) .then( (response) => {
        console.log(response)
      })
    }

    /*users comment gets displayed*/
    apiClient.comment() .then((response) =>{
    document.getElementById("comment-section").innerHTML = response
    })

    return (
        <section class = "index-banner" >
            <div>
                <label>Comment</label>
                <textarea name="comment" id= "comment" rows="10" tabIndex = "4"onChange = {e => {inputComment(e.target.value)}}></textarea>
                <button onClick={onPost}>Post</button>
            </div>            
            <div>
                <body id = "comment-section" ></body>
            </div>
        </section>
    ) 
    
}

【问题讨论】:

  • 为什么是document.getElementById("comment-section").innerHTML = response
  • 然后在 api 调用类似这样的.then((response) =&gt; response.json())
  • 你为什么要这样使用const [comment, inputComment] = useState ('')的useState,你应该这样使用const [comment, setcomment] = useState ('')

标签: javascript mysql reactjs express axios


【解决方案1】:

请求确定通过了吗?您可以在浏览器 DevTools 中的网络选项卡上进行验证。

我可以提出一些关于更好地使用 React 的建议。

  1. 当响应返回时,使用useState将其添加到组件中
  • 当有状态更新时组件会自动重新渲染
  • (这里你不需要document.getElementById
  1. 您也可以使用useRef 方法
  • 最受欢迎的“React 方式”document.getElementById

1。 useState:

function Forum() {
    
    const [comment, setComment] = useState ('')
    const [postedComment, setPostedComment] = useState ('')

    const onPost = (event) => {  
        event.preventDefault()
        apiClient
            .forum(comment)
            .then( (response) => {
                console.log(response.data)
                // this should trigger a rerender, in the <div>{postedComment}</div>

                // assuming your response contains the posted comment:
                setPostedComment(response.data)
            })
            .catch( error => console.log(error) /* handle Exception here */)
    }
    
    return <div>
        <label>Comment</label>
        <textarea
            name="comment"
            id="comment"
            rows="10"
            tabIndex ="4"
            onChange={e => {inputComment(e.target.value)}}>
         </textarea>
    
         <button onClick={onPost}>Post</button>
        <div>{ postedComment }</div>
</div>            
}

2。 useRef:

    const commentRef = useRef(null)
    // ...

    const onPost = (event) => {  
        event.preventDefault()
        apiClient
            .forum(comment)
            .then( (response) => {
                console.log(response)
                // assuming your response contains the posted comment:
                commentRef.current.innerHTML = response
            })
            .catch( error => console.log(error) /* handle Exception here */)
    }
    


    return <div>
        {/* ... */}
        <div ref={commentRef}>
        </div>
    </div>

注意事项:

  • 我会避免使用body 元素,除了整个应用程序!

解决一些 cmets:

  • fetch 使用 response.json()
  • axios 使用 response.data

【讨论】:

  • 你是对的,但我不确定response.json() axios 是否用于请求api,static async comment(comm) 正在返回response.data,所以我认为setPostedComment(response) 就足够了。
  • 感谢您指出问题@antoineso 我更新了代码示例。让我知道是否一切都好,并且您同意我的回答。快乐编码:)
  • 对不起,我忘了提。我添加了两个 api 调用。 apiClient.forum 将评论发布到数据库中,apiClient.comment 从数据库中选择发布的评论。我编辑了我的帖子,以便向您展示来自我的 api 客户端和后端的完整代码,以便为您提供想法。对不起,如果我没有说清楚
  • @AmmanM 不管您的 API 现在如何工作,我想知道答案是否有助于您解决问题,即显示获取的数据? IE。我对useStateuseRef 的建议。此 POST 旨在帮助遇到与您遇到类似问题的人,无论使用何种 API。如果您同意,请告诉我,并请对提议的答案进行投票。快乐编码:)
  • @bilo-io 我尝试使用您推荐的一些方法,但 cmets 没有出现。也许这是我输入代码的方式,但还是感谢您的建议
猜你喜欢
  • 1970-01-01
  • 2013-06-05
  • 1970-01-01
  • 1970-01-01
  • 2017-07-31
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多