0
  • 我正在使用 firestoreConnect() 将来自 firestore 的数据与 redux 同步。

  • 我通过 state.firestore.ordered 从 firestore 获取了一组员工对象

  • 员工的形状是这样的:

    {
      id: 'XtVe567...',
      name: {
        first: 'John',
        last: 'Doe'
      }
    }
    
  • 在 mapStateToProps 中,我需要先转换此数据的形状,然后再将其返回并通过 props 将其传递给组件

    function mapStateToProps(state) {
    
      const schedules = state.firestore.ordered.employees
        .map(employee => ({
          id: employee.id,
          name: {
            first: employee.name.first,
            last: employee.name.last
          },
          schedule: [null, null, null, null, null, null, null]
        }));
    
      const rota = {
       id: null,
       date: moment(),
       notes: null,
       events: [null, null, null, null, null, null, null],
       published: null,
       body: schedules
      };
    
      return {rota}
    }
    
  • 这导致:TypeError:无法读取未定义的属性“地图”

  • 我知道这是因为获取数据是异步的,并且在我映射 state.firestore.ordered.employees 时,employees 属性 === undefined 是不可迭代的

所以,我的问题是你如何使用异步数据进行这种数据转换?有没有办法暂停 mapStateToProps 的执行并等待数据在映射之前返回?

如果这个问题难以理解,请提前致谢和抱歉,这是我第一次发帖。

4

2 回答 2

0

您的组件应该对基础数据的更改做出反应。所以你可以渲染这样的东西:

getSchedules(emps) {
 return emps.map(employee => <SomeEmployeeRenderingComponent emp={employee} /> );
}
render() {
  return (
   <div>{this.getSchedules(this.props.employees).bind(this)}</div>
  )
}

mapstatetoprops 变为:

function mapStateToProps(state) {

  const rota = {
   id: null,
   date: moment(),
   notes: null,
   events: [null, null, null, null, null, null, null],
   published: null,
   employees: state.firestore.ordered.employees
  };

  return rota
}
于 2019-03-30T23:06:55.040 回答
0

为了快速使其工作,您可以执行以下操作:

function mapStateToProps(state) {

    const employees = state.firestore.ordered.employees;

    const schedules = employees
        ? employees.map(employee => ({
            id: employee.id,
            name: {
                first: employee.name.first,
                last: employee.name.last
            },
            schedule: [null, null, null, null, null, null, null]
        }))
        : undefined;

    const rota = {
        id: null,
        date: moment(),
        notes: null,
        events: [null, null, null, null, null, null, null],
        published: null,
        body: schedules
    };

    return { rota }
}

然后,在您的组件中,您可以检查 rota 对象的 schedules 属性,如果它仍然未定义,则呈现一些内容以指示尚未加载数据。

尽管如此,将如此复杂的逻辑放入mapStateToProps其中对我来说是一种反模式。您可以使用选择器模式使您的代码更有条理。

于 2019-03-31T12:54:02.490 回答