gpt4 book ai didi

reactjs - React useState 设置初始值无效

转载 作者:行者123 更新时间:2023-12-05 08:52:05 30 4
gpt4 key购买 nike

下面是我的功能组件与问题相关的代码,

如何在 useState() 钩子(Hook)中对数据进行一些处理后设置初始值?

const data = props.data ? props.data : {};
const statusOptions = [
{ label: "Active", value: "active" },
{ label: "Inactive", value: "inactive" },
{ label: "Complete", value: "completed" },
];
const defaultStatus = statusOptions.filter(
option => option.value === data["status"],
)[0];

//This does not work
const [status, setStatusValue] = useState(defaultStatus);
console.log(status); //undefined

//Below works
const [status, setStatusValue] = useState({
label: "Complete",
value: "completed",
});
console.log(status); //{label:"Complete",value:"completed"}

最佳答案

如果你遇到同样的问题,我想这可能对你有帮助

The initialState argument is the state used during the initial render. In subsequent renders, it is disregarded.

因此,如果数据不可用,我们不应该渲染组件,因为 initialState 可能为空,并且此空值将保留在那里以供后续渲染。

希望这对您有所帮助。

关于reactjs - React useState 设置初始值无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57570237/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com