如何改变反冲选择器的状态

How to change state in recoil selector

我正在尝试以类似于正常状态更改的方式更改选择器中的状态,但我不知道自己做错了什么。有人可以帮助我吗?

这是我的原子:

export interface iBook {
  id: number;
  title: string;
}

const initState: iBook[] = [{ id: 1, title: "a" }];

export const bookState = atom({
  key: "bookState",
  default: initState,
});

现在选择器不起作用

export const onChange = selector({
  key: "onChange",
  get: ({ get }) => get(bookState),
  set: ({ set, get }, id) => {
    const books= get(bookState);
    set(
      bookState,
      books.map((book) => {
        if (book.id === id)
          return {
            ...book,
            title: "b",
          };
      })
    );
  },
});

它在“bookState”上显示错误

Argument of type 'RecoilState<iBook[]>' is not assignable to parameter of type 'RecoilState<({ value: number; title: string; } | undefined)[]>'. Types of property '__cTag' are incompatible. Type '(t: iBook[]) => void' is not assignable to type '(t: ({ title: string; id: number; } | undefined)[]) => void'. Types of parameters 't' and 't' are incompatible. Type '({ title: string; id: number; } | undefined)[]' is not assignable to type 'iBook[]'. TS2345

这是在组件中工作的钩子,但我希望它在选择器中:

   setBooks(
      books.map((book) => {
        if (book.id === id)
          return {
            ...book,
            title: "b",
          };
        return book;
      })
    );

如果 ID 不匹配,那么您 return 不在图书对象中,因此您 return 未定义。 Return 图书对象:

export const onChange = selector({
  key: "onChange",
  get: ({ get }) => get(bookState),
  set: ({ set, get }, id) => {
    const books= get(bookState);
    set(
      bookState,
      books.map((book) => {
        if (book.id === id) {
          return {
            ...book,
            title: "b",
          };
        }
        return book;
      })
    );
  },
});