最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - "useState" cannot be called inside a callback. How to use state on "useCallback&quot

programmeradmin5浏览0评论

I want to update state in Child ponent but it doesn't work. Actually, there're a lot of items. And I want to list each item with map.

The error:

React Hook "useState" cannot be called inside a callback. React Hooks must be called in a React function ponent or a custom React Hook function

The code:

const renderItems = useCallback(() => {
  return items.map((item, idx) => {
    const { name } = room
    const [isCopiedURL, setIsCopiedURL] = useState(false)

    return (
      <li key={idx}>
        <CopyToClipboard
          text={item.name}
          onCopy={() => setIsCopiedURL(true)}
        >
          {item.name}
        </CopyToClipboard>
      </li>
    )
  })
}, [items])

I want to update state in Child ponent but it doesn't work. Actually, there're a lot of items. And I want to list each item with map.

The error:

React Hook "useState" cannot be called inside a callback. React Hooks must be called in a React function ponent or a custom React Hook function

The code:

const renderItems = useCallback(() => {
  return items.map((item, idx) => {
    const { name } = room
    const [isCopiedURL, setIsCopiedURL] = useState(false)

    return (
      <li key={idx}>
        <CopyToClipboard
          text={item.name}
          onCopy={() => setIsCopiedURL(true)}
        >
          {item.name}
        </CopyToClipboard>
      </li>
    )
  })
}, [items])
Share Improve this question asked May 28, 2020 at 7:29 k10ak10a 1,0872 gold badges13 silver badges35 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

You can convert the mapped return value to a ponent and then use useState within it since hooks are meant to be used within functional ponents.

According to the rules of rules you can use them within functions such as map in your case

const Item = ({room, item}) => {
    const { name } = room
    const [isCopiedURL, setIsCopiedURL] = useState(false)

    return (
      <li key={idx}>
        <CopyToClipboard
          text={item.name}
          onCopy={() => setIsCopiedURL(true)}
        >
          {item.name}
        </CopyToClipboard>
      </li>
    )
}

...
const renderItems = useCallback(() => {
  return items.map((item, idx) => {
     return <Item room={room} item={item} key={idx} />
  })
}, [items])
...

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论