React钩子"useState"无法在回调函数中调用。

4

有没有其他方法可以在不将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>
    );
  });
}

是的,只需将 map 内部的 jsx 制作成另一个组件即可。 - Keith
2个回答

2
您可以将数组放入状态中:
const [countArr, setCountArr] = useState(
  () => new Array(slimy.length).fill(0)
);
return slimy.map(function(item, i){
  <ListItem key={item.createdAt} style={{ display: 'flex', justifyContent: 'center'}}>
    <div>
      <p>{countArr[i]}</p>
      <button onClick={() => { setCountArr(
        countArr.map((count, j) => i === j ? count + 1 : count)
      ) }} />
      </div>
  </ListItem>)
});

2

您可以定义自定义组件。

{
  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>
   )
}

那么,我该如何在单独的组件中使用列表中的项目? - Raphael Inyang
例如,这个列表包含了一些名字,我应该在哪里渲染这个名字列表? - Raphael Inyang
就像 item.createdAt 一样,我在哪里使用 item.names - Raphael Inyang
你会在答案正确时点赞吗? - Prime
让我们在聊天中继续这个讨论 - Prime
是的,当然会的,如果我尝试过并且它有效。 - Raphael Inyang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接