0

我正在尝试更改选择器中的状态,类似于正常状态更改,但我无法弄清楚我做错了什么。有人能帮我吗?

这是我的原子:

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”上显示错误

'RecoilState<iBook[]>' 类型的参数不可分配给'RecoilState<({ value: number; title: string; } | undefined)[]>' 类型的参数。属性“__cTag”的类型不兼容。类型 '(t: iBook[]) => void' 不能分配给类型 '(t: ({ title: string; id: number; } | undefined)[]) => void'。参数“t”和“t”的类型不兼容。类型 '({ title: string; id: number; } | undefined)[]' 不可分配给类型 'iBook[]'。TS2345

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

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

1 回答 1

1

如果 id 不匹配,则不会返回 book 对象,因此返回 undefined。返回图书对象:

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;
      })
    );
  },
});
于 2021-04-10T12:11:57.023 回答