【问题标题】:React Fetch with State Value使用状态值响应获取
【发布时间】:2021-11-05 05:44:50
【问题描述】:

我有两个不同的 API URL。我可以使用 /api/current_user 获取当前用户的 ID 并保存到“currentuser”状态。我想从 MySQL 中获取所有 currentuser's。我的 API URL 有效。但我无法使用 currentuser 状态变量获取。

此链接返回当前用户的 ID。它有效。

  useEffect(()=>{
    
    fetch('http://localhost:8000/api/current_user/', {
      headers: {
        Authorization: `JWT ${localStorage.getItem('token')}`
      }
    })
      .then(res => res.json())
      .then(json => {
        setCurrentuser(json.id);
      });
  
  
},[]) 

然后我想将该 ID 与 currentuser 状态一起使用。

 Axios.request({
      method: 'POST',  
      url: 'http://localhost:3001/api/post',
      data: {
        curus: `${currentuser}`     // I'm trying to use currentuser state on here.
      },
     })

    .then(response => {
      return response.data;
  })
    .then(data => {
      let tmpArray2 = []
      const tmpArray = []
bla bla bla ...

最后请求载荷返回curus: ""

所以它有一个空值。我可以在返回函数中使用这个状态值。

这也是我节点服务器的 index.js:

app.post('/api/post', (req, res) => {
    const currentt = req.body.curus
    const sqlSelect = "SELECT * FROM messagestable WHERE sender='" + currentt + "' OR recipient ='" + currentt + "' ";
    db.query(sqlSelect, (err, result) => {
        res.send(result);
        console.log(currentt)
    });

})

我想从 MySQL 中获取所有消息,但只针对当前用户。不是所有用户的消息。你能帮帮我吗?非常感谢!

【问题讨论】:

  • 给我更多的上下文:第一个填充 currentuser 的 fecth 是在组件加载时完成的。但是当Axios.requestfill 被解雇的时候呢?点击按钮?在组件的加载?你把它写在组件的主体上?
  • 'currentuser' 状态是否与 Axios 请求处于相同的上下文中?对我来说,要么在定义当前用户状态之前启动 axios 请求,要么用户状态为 null,因为不在 Axios 请求组件上下文中。此外,您的服务器容易受到 SQL 注入的攻击,check this link
  • 我在 useEffect() 中同时使用它们。他们接连而来。第一个是“ fetch('localhost:8000/api/current_user', {....”,第二个代码块是底部。

标签: reactjs axios react-hooks fetch


【解决方案1】:

您不能连续调用fetch 和Axios.request,因为setCurrentuser 是异步的,并且当您在Axios.request 中使用currentuser 时,您不知道currentuser 是否具有最后一个值。

以这种方式将fetch 和Axios.request 拆分为2 个useEffect 会更好:

useEffect(()=>{  //<-- this will be fired on component's loading
    
    fetch('http://localhost:8000/api/current_user/', {
      headers: {
        Authorization: `JWT ${localStorage.getItem('token')}`
      }
    })
      .then(res => res.json())
      .then(json => {
        setCurrentuser(json.id);
      });
  
  
},[]) 

useEffect(() => { //<-- this one will be fired every time you change currentuser and will contains the very last value of currentuser
  Axios.request({
  method: 'POST',  
  url: 'http://localhost:3001/api/post',
  data: {
    curus: `${currentuser}`
  },
 })

.then(response => {
  return response.data;
})
.then(data => {
  let tmpArray2 = []
  const tmpArray = []
  bla bla bla ...

}, [currentuser])

【讨论】:

  • 哦,这太可以理解了。你比我所有的老师都好!谢谢大家。现在我要寻找 SQL 注入问题。你是最棒的!
  • @HighPriv 非常感谢。有一个非常好的编码 =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
  • 2016-02-19
  • 2017-12-13
  • 2016-02-07
  • 2017-09-26
  • 2011-10-17
相关资源
最近更新 更多