Как преобразовать асинхронные данные в mapStateToProps?

'whatsmypurpose' дает новому подклассу его имя типа. Из документов:

collections.namedtuple ( typename , field_names, verbose = False, rename = False) Возвращает новый подкласс подставок с именем typename .

Вот пример:

>>> from collections import namedtuple
>>> Foo = namedtuple('Foo', ['a', 'b'])
>>> type(Foo)
<class 'type'>
>>> a = Foo(a = 1, b = 2)
>>> a
Foo(a=1, b=2)
>>> Foo = namedtuple('whatsmypurpose', ['a', 'b'])
>>> a = Foo(a = 1, b = 2)
>>> a
whatsmypurpose(a=1, b=2)
>>> 

Установите для параметра verbose значение True, и вы можете выполнить полный whatsmypurpose определение класса.

>>> Foo = namedtuple('whatsmypurpose', ['a', 'b'], verbose=True)
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict

class whatsmypurpose(tuple):
    'whatsmypurpose(a, b)'

    __slots__ = ()

    _fields = ('a', 'b')

    def __new__(_cls, a, b):
        'Create new instance of whatsmypurpose(a, b)'
        return _tuple.__new__(_cls, (a, b))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new whatsmypurpose object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def _replace(_self, **kwds):
        'Return a new whatsmypurpose object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('a', 'b'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % list(kwds))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        return self.__class__.__name__ + '(a=%r, b=%r)' % self

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values.'
        return OrderedDict(zip(self._fields, self))

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)

    a = _property(_itemgetter(0), doc='Alias for field number 0')

    b = _property(_itemgetter(1), doc='Alias for field number 1')
0
задан Fellowwws 30 March 2019 в 22:32
поделиться

2 ответа

Чтобы быстро заставить его работать, вы можете просто сделать что-то вроде:

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 }
}

Затем, в своем компоненте, вы можете проверить атрибут расписаний объекта ротации и, если он все еще не определен, визуализировать что-то, чтобы указать, что данные еще не загружены.

Тем не менее, введение такой сложной логики в mapStateToProps является для меня антипаттерном. Вы можете использовать шаблон селектора, чтобы сделать ваш код более организованным.

0
ответ дан Marcin Szewczyk 30 March 2019 в 22:32
поделиться

Ваш компонент должен реагировать на изменения в базовых данных. Таким образом, вы можете сделать что-то вроде этого:

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
}
0
ответ дан jsdeveloper 30 March 2019 в 22:32
поделиться
Другие вопросы по тегам:

Похожие вопросы: