gpt4 book ai didi

javascript - MobX - 从计算值中过滤 asMap?

转载 作者:行者123 更新时间:2023-11-29 23:56:56 24 4
gpt4 key购买 nike

我正在尝试 asMap 并希望输出与 coverType 匹配的书名:

这是BookStore:

class BookStore {
@observable coverType = 'soft';
@observable booksByIdMap = asMap({
"88cd7621": {
"id": "88cd7621",
"title": "The Secret",
"coverType": 'soft'
},
"88cd7622": {
"id": "88cd7622",
"title": "The Alchemist",
"coverType": 'hard'
},
"88cd7623": {
"id": "88cd7623",
"title": "Javascript",
"coverType": 'soft'
}
});

@computed get byCoverType() {
return this.booksByIdMap.filter(book => book.coverType == this.coverType);
}
}

这是用户界面:

const bookStore = new BookStore();

const BookViewItem = observer(({book}) =>
<li>
{book.title}
</li>
);

@observer
class BookView extends Component {
render() {
return <div>
<h1>Books With Cover Type: {bookStore.coverType}</h1>
<ul>
{bookStore.byCoverType().map(book =>
<BookViewItem book={book} key={book.id} />
)}
</ul>
</div>
}
}

但它不会根据当前的 coverType 值呈现书名。

这是一个 fiddle : https://jsfiddle.net/ob7v1gk5/

如何使用计算的 Bookstore.byCoverType 过滤结果输出书名?

最佳答案

MobX 映射不是数组,因此它没有过滤器和其他特定于数组的方法。检查documentation to see what methods you can use .

例如,您可以使用 values 方法,然后对结果数组 like this 使用 filter :

class BookStore {
@observable coverType = 'soft';
@observable booksByIdMap = asMap({
"88cd7621": {
"id": "88cd7621",
"title": "The Secret",
"coverType": 'soft'
},
"88cd7622": {
"id": "88cd7622",
"title": "The Alchemist",
"coverType": 'hard'
},
"88cd7623": {
"id": "88cd7623",
"title": "Javascript",
"coverType": 'soft'
},
});

@computed get byCoverType() {
return this.booksByIdMap.values().filter(b => b.coverType === this.coverType);
}
}

关于javascript - MobX - 从计算值中过滤 asMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41354427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com