【发布时间】:2021-05-24 15:55:15
【问题描述】:
我目前有这样的事情:
const Edit_History = (props) => {
var thing = ''
useEffect(() => {
const id = props.match.params.id
if (thing === '')
axios.get(`http://localhost:3010/v0/student/${id}/${id}`)
.then(({ data }) => {
thing = data
console.log(thing)
})
}, [])
const submitHandler = async (e) => {
console.log(thing)
etc...
}
当我第一次在 useEffect 中打印出“事物”时,我得到了我想要的值。但是当我尝试使用提交处理程序在提交时打印它时,它会打印出一个空字符串,即使我没有在 useEffect 之外修改“字符串”的值。我不知道为什么会发生这种情况。
编辑:
我最初尝试使用 useState
const Edit_History = (props) => {
const [thing, setThing] = useState("")
useEffect(() => {
const id = props.match.params.id
axios.get(`http://localhost:3010/v0/student/${id}/${id}`)
.then(({ data }) => {
setThing(data)
console.log(thing)
})
}, [])
const submitHandler = async (e) => {
console.log(thing)
etc...
}
但是在 setThing(data) 之后,事情仍然是未定义的,这就是为什么我尝试使用 var thing 而不是 useState。
【问题讨论】:
-
使用 useState 而不是普通的 var。
-
@ggorlen 那是我最初尝试的,但由于某种原因,在 setThing 之后“东西”未定义
-
您可以编辑帖子以显示该代码吗?谢谢。
-
@ggorlen 我刚刚更新了帖子
标签: reactjs