2

我正在使用 zustand 和 typescript。我的代码出现此错误

Property 'filter' does not exist on type 'object'.ts(2339)

我不知道如何解决这个问题。我正在从我的 useStore 库创建一个对象。我尝试使用“类型”,但它在代码编辑器错误中引发了这些 错误

TS

import React from "react";
import "./App.css";
import create from "zustand";

type PkState = {
    filter: "",
    pokemon: [],
  }


const useStore = create((PkState) => ({
 

  PkStateFilter: (filter) =>
    PkState((state) => ({
      ...state,
      filter,
    })),

  PkStatePokemon: (pokemon) =>
    PkState((state) => ({
      ...state,
      pokemon,
    })),
}));

//  input
const FilterInput = () => {
  const filter = useStore((state) => state.filter);
  const PkStateFilter = useStore((state) => state.PkStateFilter);
  return (  <input value={filter}  onChange=((evt)=>PkStateFilter(evt.target.value))  />
  )
  


};

function App() {
  return <div className="App"></div>;
}

export default App;
4

2 回答 2

2

您需要为您的商店定义一个类型。

import React from "react";
import "./App.css";
import create from "zustand";

type State = {
  filter: string;
  pokemon: Array<string>;
  setFilter: (filter: string) => void;
  setPokemon: (pokemon: Array<string>) => void;
};

// You have to use the type here
const useStore = create<State>((set) => ({
  filter: "", // set initial values here
  pokemon: [],

  setFilter: (filter) =>
    set((state) => ({
      ...state,
      filter
    })),

  setPokemon: (pokemon) =>
    set((state) => ({
      ...state,
      pokemon
    }))
}));

//  input
const FilterInput = () => {
  const filter = useStore((state) => state.filter);
  const setFilter = useStore((state) => state.setFilter);
  return (
    <input value={filter} onChange={(evt) => setFilter(evt.target.value)} />
  );
};

function App() {
  return (
    <div className="App">
    </div>
  );
}

export default App;
于 2021-05-21T23:21:32.077 回答
0

我不确定这是否可行,请尝试filter在下一个方式分散注意力:

 const { filter } = useStore((state) => state);

您还可以useStore使用 console.log 进行调试,以检查返回的内容:

 const returnedState = useStore((state) => state);

 // Check does `filter` exists in state
 console.warn('returnedState', returnedState);

于 2021-05-21T23:28:51.880 回答