【发布时间】: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