繁体   English   中英

带有回调的 useState 类型 - 类型没有调用签名

[英]type for useState with callback - Type has no call signatures

我正在使用带有回调的useState

interface Props {
  label: string;
  key: string;
}

const [state, setState] = useState<Props[]>([]);


setState((prev : Props[]) => [...prev, newThing])

我得到错误:

2349: This expression is not callable. Type 'Props' has no call signatures.

我不确定如何在 Props 接口/类型中定义调用签名,解决此问题的最佳方法是什么?

编辑:

这就是我在代码中使用它的方式:

界面:

interface TagProps {
  left: string;
  top: string;
  backgroundColor: string;
  rotation: number;
  label: string;
  key: string;
}

主页.tsx

const Home: FC<TagProps> = (setState, state: TagProps[]) => {
  const createTag = (e: any) => {
    const tagSpec = {
      left: e.clientX + "px",
      top: e.clientY + "px",
      backgroundColor: randomColour(colors),
      rotation: randomNumber(-20, 20),
      label: tech[randomNumber(0, tech.length - 1)],
      key() {
        return this.label + this.backgroundColor;
      },
      position: "absolute",
    };
    setState((prev: TagProps[]) => [...prev, tagSpec]);
  };

...

}

应用程序.tsx

function App() {
  const [tag, setTag] = useState<TagProps[]>([]);

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Layout />}>
          <Route index element={<Home setState={setTag} state={tag} />} />
          <Route path="/blog" element={<Blog />} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

你必须描述你的道具

// from
const Home: FC<TagProps> = (setState, state: TagProps[]) => {

// to
const Home: FC<TagProps> = ({ setState, state }) => {

我也不会将setState传递给组件

React 功能组件的属性在第一个参数下,你可以这样做来获取它们

const Home = (props) => {
  const { state, setState } = props;

  // setState(...)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM