【问题标题】:Using a state variable in Axios put request in React Native在 Axios 中使用状态变量将请求放入 React Native
【发布时间】:2021-10-18 06:35:46
【问题描述】:

我在 React native 中修改状态变量 (setTokens(tokens - 1)),然后在 axios PUT 请求 (library_tokens: tokens) 中使用修改后的变量。 问题是,put请求成功了,但是在PUT请求之后,它把变量的旧值而不是修改后的值放到了数据库中

以下是代码:

const [tokens,setTokens] = useState(0)

const lendBook = book => {

// Add book to the IssueReturn collection in the database

issuesApi
  .post('/bookissue', {
    booksIssued: book._id,

    image: book.image,
    user: context.stateUser.user.userId,
  })
  .then(response => {
    if (response.status === 200) {

      // Decrement user's library token
      setTokens(tokens - 1);
     
      // Modify the user's library tokens
      userProfileApi
        .put(
          `/${context.stateUser.user.userId}`,
          {
            library_tokens: tokens,
          },
          {
            headers: {Authorization: `Bearer ${jwtToken}`},
          },
        )
        .then(response => {
          console.log('tokens', tokens);
        });

     
    }
  })
  .catch(err => {
    console.log(err);


  });

};

【问题讨论】:

    标签: react-native axios react-hooks


    【解决方案1】:

    你可以像这样使用 useEffect。

    useEffect(() => {
      console.log(tokens) // do something after state has updated
    }, [tokens])
    

    状态更新后会调用useEffect,所以你可以在useEffect里面调用userProfileApi。

    【讨论】:

      【解决方案2】:

      setTokens 它不是同步函数。之后执行的代码不会有更新的状态。要么使用局部变量来存储token - 1 的结果,要么使用useEffect 钩子。

      【讨论】:

        猜你喜欢
        • 2020-04-05
        • 2021-10-20
        • 2019-07-24
        • 2020-10-17
        • 2018-02-25
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 2018-08-31
        相关资源
        最近更新 更多