如何遍历Mobx Observable Map的键(无需转为普通JS对象)
toJs() Great question! You don’t need to convert your Observable Map to a plain JavaScript object to iterate over it in React—MobX’s Observable Map implements the standard ES6 Map interface, so you can use its built-in methods directly. Here’s how to make it work while keeping reactivity intact:
First, ensure your component is wrapped in MobX’s observer HOC (higher-order component). This tells MobX to track observable changes and re-render the component when your map updates:
import { observer } from 'mobx-react'; @observer class ComponentB extends React.Component { // Your component logic here }
Now, you have two clean ways to iterate over your Observable Map in the render method:
Option 1: Iterate using keys()
Use the map’s keys() method to get an iterator of all keys, convert it to an array (with Array.from or the spread operator), then map over the array to render each key-value pair:
render() { const { store } = this.props; // Adjust based on how you access your store instance return ( <div> {Array.from(store.myMap.keys()).map(key => ( <p key={key}>{key}: {store.myMap.get(key)}</p> ))} </div> ); }
Or with the spread operator for brevity:
{[...store.myMap.keys()].map(key => ( <p key={key}>{key}: {store.myMap.get(key)}</p> ))}
Option 2: Use entries() for direct key-value pairs
Even cleaner, use entries() to get an iterator of [key, value] pairs. This lets you destructure both values directly without calling get(key):
render() { const { store } = this.props; return ( <div> {Array.from(store.myMap.entries()).map(([key, value]) => ( <p key={key}>{key}: {value}</p> ))} </div> ); }
Again, spread operator works here too:
{[...store.myMap.entries()].map(([key, value]) => ( <p key={key}>{key}: {value}</p> ))}
Why this works:
MobX’s Observable Map is a reactive wrapper around the native ES6 Map, so all standard Map methods (keys(), entries(), values(), forEach()) are fully supported. Since your component is an observer, MobX will automatically track access to the map’s keys and values, triggering a re-render whenever entries are added, removed, or updated—no need for toJs()!
内容的提问来源于stack exchange,提问作者jeanpaul62

