无法将一个组件的状态发送到nextjs中的其他组件,出现此错误:ncaught TypeError: setSelectedTag is not a function at onClick

问题描述 投票:0回答:1

我已经使用 useState hook 创建了状态,并且我尝试将 setState 函数作为道具发送给子组件,但是当我在按钮“onclick”中使用该函数时,它给了我一个错误: setSelectedTag 不是 onClick 的函数

page.tsx:


export default function Home(post: Post) {
  //creating state
  const [selectedTag, setSelectedTag] = useState("All");
//passing the state as props. in a child component
 <BlogFilter
        selectedTag={selectedTag}
        setSelectedTag={setSelectedTag}
        tags={arrString}
      ></BlogFilter>


blogfilter.tsx:


import React from "react";

export default function BlogFilter(
  tags: any,
  selectedTag: any,
  setSelectedTag: any
) {
  if (tags?.length === 0) {
    return null;
  }
  //spliting the string , also converting the string into an array.
  const duplicateArr = tags?.tags.split(",");
  // console.log(duplicateArr);
  //removing duplicates from array
  const withoutDuplicates = duplicateArr?.filter(
    (value: any, index: any, array: string | any[]) =>
      array.indexOf(value) === index
  );

  tags = withoutDuplicates?.map((t: any) => t.trim());

  // console.log(tags);

  return tags?.map((tag: any) => (
    <button
      key={tag}
      className={`ml-2 rounded-full hover:bg-indigo-600 
      ${selectedTag === tag ? "active:bg-indigo-700" : " bg-indigo-500"}
      focus:outline-none focus:ring focus:ring-indigo-300
      px-3 text-[11px] font-light text-white`}
**      onClick={() => {
        setSelectedTag(tag);
**
        console.log(typeof tag);
      }}
    >
      # {tag}
    </button>
  ));
}
reactjs next.js react-hooks mdx nextjs13
1个回答
0
投票

在 page.tsx 文件中,当您将 props 发送到 BlogFilter 组件时:

<BlogFilter
   selectedTag={selectedTag}
   setSelectedTag={setSelectedTag}
   tags={arrString}
/>

代替:

export default function BlogFilter(tags, setSelectedTag, selectedTag) {
   // ...
}

您应该使用:

export default function BlogFilter({ tags, setSelectedTag, selectedTag }) {
   // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.