Skip to content

observer如何监听map对象 #2239

Answered by liuyib
xmsz asked this question in Q&A
Jun 29, 2023 · 2 comments · 2 replies
Discussion options

You must be logged in to vote

目前 useReactive 不支持这样使用:

const App = () => {
  const state = useReactive(new Map());

  // ❌ will throw: "TypeError: Method Map.prototype.size called on incompatible receiver #<Map>"
  return <div>{state.size}</div>;
};

下面这种使用方式不会报错,但是没法引起组件重新渲染,所以还是不会正常工作:

const App = () => {
  const state = useReactive({
    a: new Map(),
  });

  return (
    <div>
      {/* ✅ no error thrown */}
      {state.a.size}

      {/* ❌ can't cause the component to re-render */}
      <button onClick={() => state.a.set('a', 1)}>update</button>
    </div>
  );
};

综上,目前 useReactive 不兼容 Map, Set。我看了下,想要兼容的话, 处理起来很麻烦,需要实现类似
observer-util
这个包的能力,暂时先不考虑了,我在文档里加上 FAQ

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
1 reply
@xmsz
Comment options

Comment options

You must be logged in to vote
1 reply
@liuyib
Comment options

Answer selected by xmsz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants