【发布时间】:2021-01-12 12:20:33
【问题描述】:
我对 ReactJS 中的钩子有疑问 正如你在这里看到的,我定义了一个应该从子组件调用的道具 但是当我想通过调用更改组件来更改值时,它不起作用并且我的状态没有设置。 有人能帮我吗? 别忘了阅读 cmets
import React, {useState} from "react";
import Collection from "./Collection";
import ReminderPeriod from "./ReminderPeriod";
function SingleReminderPage() {
const [collection, setCollection] = useState(null);
const setSelectedCollection = (e) => {
setCollection(e);
console.log(e); // returns the true value
console.log(collection); // returns null
}
return(
<div>
<Collection onChoosed={(e) => setSelectedCollection(e)}/>
</div>
)
}
export default SingleReminderPage;
【问题讨论】:
-
你能把
Collection组件的代码贴在你调用函数的地方吗? -
setCollection不会同步更新状态。当这个console.log(collection);被执行时,状态可能不会更新,这就是它仍在打印null的原因。
标签: reactjs react-hooks components use-state