英文:
UseState always return Previous value
问题
当我选择一个值时,它总是返回先前的值。不返回我选择的值。
我希望当我选择值时,它能快速反映并存储当前值。
const [postsPerPage, setPostsPerPage] = useState(15);
const handleChange = async (event) => {
let data = (document.getElementById("dropzonee")).value;
setPostsPerPage(data);
console.log(postsPerPage);
}
<span>每页行数</span>
<select
id="dropzonee"
name="changedValue"
onChange={handleChange}
value={postsPerPage}
>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
</select>
英文:
When I select a value it always returns the previous value. Not returning which I selected.
I want, when I select value it quickly reflects and store current value.
const [postsPerPage, setPostsPerPage] = useState(15);
const handleChange = async (event) => {
let data = (document.getElementById("dropzonee")).value
setPostsPerPage(data)
console.log(postsPerPage)
}
<span>Rows Per Page</span>
<select id="dropzonee"
name="changedValue"
onChange={handleChange}
value={postsPerPage}
>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
</select>
答案1
得分: 1
只需使用 event.target.value
const [每页帖子数, 设置每页帖子数] = useState(15);
const 处理变化 = async (事件) => {
设置每页帖子数(事件.target.value)
console.log(每页帖子数)
}
或者如果你不使用 async/await
,可以像这样使用
const [每页帖子数, 设置每页帖子数] = useState(15);
<span>每页行数</span>
<select id="dropzonee"
name="changedValue"
onChange={(e) => 设置每页帖子数(e.target.value)}
value={每页帖子数}
>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
</select>
英文:
Just use event.target.value
const [postsPerPage, setPostsPerPage] = useState(15);
const handleChange = async (event) => {
setPostsPerPage(event.target.value)
console.log(postsPerPage)
}
or if you don't use asyns/await
, use like this
const [postsPerPage, setPostsPerPage] = useState(15);
<span>Rows Per Page</span>
<select id="dropzonee"
name="changedValue"
onChange={(e) => setPostsPerPage(e.target.value)}
value={postsPerPage}
>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
</select>
答案2
得分: 0
尝试使用以下代码而不是
let data = (document.getElementById("dropzonee")).value
,
let data = event.target.value
。
它将始终显示所选值。但即使如此,console.log(postsPerPage)将始终记录先前的值,因为setState函数是异步工作的,在那一刻状态尚未真正更新。只需记录event.target.value以确保。
英文:
Instead of
let data = (document.getElementById("dropzonee")).value
,
try
let data = event.target.value
.
It will always show selected value. But even so, console.log(postsPerPage) will always log previous value, because setState function works asynchronously, and it that moment state didn't really updated. Just log event.target.value to ensure
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论