gpt4 book ai didi

javascript - 无法在回调中调用 React Hook "useState"

转载 作者:行者123 更新时间:2023-12-03 23:01:28 26 4
gpt4 key购买 nike

有没有另一种方法可以做到这一点,而不必将 useState 变量放在 map 函数之外?

const slimy = [];
{
slimy.map(function (item) {
const [count, setCount] = useState("");

return (
<ListItem
key={item.createdAt}
style={{ display: "flex", justifyContent: "center" }}
>
<div>
<p>{count}</p>

<button onClick={() => setCount(count + 1)} />
</div>
</ListItem>
);
});
}

最佳答案

您可以定义自定义组件。

{
slimy.map(function (item) {
return (
<CustomItem key={item.createdAt} names={item.names} />
);
});
}
const CustomItem = (props) => {
console.log(props.names); // <----------------
const [count, setCount] = useState(0);
return (
<ListItem style={{ display: "flex", justifyContent: "center" }}>
<div>
<p>{count}</p>
<button onClick={() => setCount(count + 1)} />
</div>
</ListItem>
)
}

关于javascript - 无法在回调中调用 React Hook "useState",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65450813/

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