我有一个 React 应用程序,我正在尝试使用 Reux-ORM,但我正在努力使用选择器。我有一个带有标准化数据的简单应用程序
// /models/team.js
import { Model, many, attr } from 'redux-orm';
import Player from './player';
class Team extends Model {
static reducer(action, Team, session) {
[...]
}
}
Team.modelName = "Team";
Team.fields = {
id: attr(),
players: many('Player;),
}
和
// /models/player.js
import { Model, attr } from 'redux-orm';
class Player extends Model {
static reducer(action, Player, session) {
[...]
}
}
Player.modelName = "Player";
Player.fields = {
id: attr(),
}
我将它们注册到 ORM 中,如下所示:
// /selectors/selector.js
import { ORM } from 'redux-orm';
import Team from '../models/team';
import Player from '../models/player';
const orm = new ORM();
orm.register(Team, Player);
export default orm;
到目前为止,一切都很好。现在我想要一个 React 组件,它呈现包含所有玩家的所有团队的列表。所以我做的第一件事就是写一个选择器:
// /selectors/selector.js
import { createSelector } from "redux-orm";
import orm from "../models/index";
export const teams = createSelector(
orm,
state => state.orm,
session => {
return session.Team.all().toRefArray();
}
);
这给出了一个团队列表,但还没有它的相关球员。teams
所以在我的组件中,如果我添加一个函数,我现在可以从我的道具中使用const mapStateToProps = state => ({teams: teams(state)});
但现在我的问题是,获得特定球队球员的最佳方式是什么?我是否将它们添加到选择器中的返回团队?还是我写一个单独的选择器?我会直接将玩家传递给组件,还是在团队组件中创建一个单独的组件?
class Teams extends React.Components {
render() {
return this.props.teams.map(team => {
/* Option 1: */
const teamPlayer = team.players // returned by initial selector
/* Option 2: */
const teamPlayers = [some call to selector based on 'team'];
/* Option 3: */
// Don't pass on the players but the id instead
return (
<Team
/* Option 1 & 2: */
players= {teamPlayers}
/* Option 3: */
teamId = {team.id} // and within the Team component make a selector call
/>
}
}
在实现上,我陷入了制作选择器的困境,找不到这种情况的示例 for redux-orm v0.19
,而且从概念上讲,我仍然不确定哪种方式是最好的选择。非常感谢所有帮助!