【问题标题】:How to 'extract' normalized data from redux store如何从 redux 存储中“提取”规范化数据
【发布时间】:2021-12-29 13:20:11
【问题描述】:

在较早的问题中,我在使用 normalizr 规范化数据以存储到我的 Redux 存储中时遇到了困难。

这是结果: https://stackoverflow.com/a/70519781/16303828

const assistant = new schema.Entity("assistants");
const dentist = new schema.Entity("dentists");
const client = new schema.Entity("clients");
const userSchema = {
  assistants: [assistant],
  dentists: [dentist],
  clients: [client]
};
const normalizedUsers = normalize(users, userSchema);

console.log(normalisedUsers) 的结果现在是:

{entities: {…}, result: {…}}
entities:
assistants: {201: {…}, 202: {…}}
clients: {1: {…}, 2: {…}}
dentists: {101: {…}, 102: {…}}
[[Prototype]]: Object
result:
assistants: (2) [201, 202]
clients: (2) [1, 2]
dentists: (2) [101, 102]
[[Prototype]]: Object
[[Prototype]]: Object

现在的问题是:如何重构 React 中的组件以显示该数据。还是我在如何规范化我的数据方面仍然存在错误,我应该在那里改变一些东西吗?

【问题讨论】:

    标签: reactjs redux normalizr


    【解决方案1】:

    你实际上并没有共享任何 React 组件,所以我只是猜测你想要做什么。你想要一个<Assistant /> 组件来显示每个助手,对吧?客户和牙医也是如此。

    假设规范化的数据现在在 redux 存储中(注意,需要 lodash),我会这样做:

    import { useSelector, shallowEqual } from 'react-redux'
    import { keys, isEmpty } from 'lodash'
    //       ^ equivalent to Object.keys() but with safety checks
    
    export function AssistantsList() {
      const assistants = useSelector((state: RootState) => keys(state.assistants), shallowEqual)
    
      if (isEmpty(assistants)) return null
      return (
        <div>
          {assistants.map(id => (
            <Assistant key={id} id={Number(id)} />
          ))}
        </div>
      )
    }
    
    // typescript stuff: ignore if not using typescript
    interface AssistantProps {
      id: number;
    }
    
    function Assistant({ id }: AssistantProps) {
      const { first_name, last_name, phone, email } = useSelector(
        (state: RootState) => state.assistants[id],
        shallowEqual
      )
    
      return (
        <div>
          <b>Assistant #{id}</b>
          <div>
            {first_name} {last_name}
          </div>
          <a href={`tel:${phone}`}>{phone}</a>
          <a href={`mailto:${email}`}>{email}</a>
        </div>
      )
    }
    
    // typescript stuff
    type AssistantState = {
      id: number;
      first_name: string;
      last_name: string;
      phone: string;
      email: string;
    }
    
    // in a real app would be ReturnType<typeof store.getState>
    // (where `store` is the redux store)
    type RootState = {
      assistants: {
        [id: number]: AssistantState
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-24
      • 2013-06-09
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      • 2020-01-21
      相关资源
      最近更新 更多