如何使用Rxjs实现切换

时间:2017-05-13 06:41:22

标签: javascript reactjs rxjs recompose

我正在学习rxjs。我为Dropdown组件创建装饰器“toggleable”。一切正常,但我不喜欢它。如何删除条件“切换/隐藏”。

使用rxjs,react.js,重构。 这是Dropdown组件的toogleable decorator。

export const toggleable = Wrapped => componentFromStream((props$) => {
// toogleHandler  called  with onClick
  const { handler: toogleHandler, stream: toogle$ } = createEventHandler();
// hideHandler called with code below
  const { handler: hideHandler, stream: hide$ } = createEventHandler();

  const show$ = Observable.merge(
    toogle$.mapTo('toogle'),
    hide$.mapTo('hide'))
          .startWith(false)
          .scan((state, type) => {
            if (type === 'toogle') {
              return !state;
            }
            if (type === 'hide') {
              return false;
            }

            return state;
          });


  return props$
    .combineLatest(
      show$,
      (props, show) => (
        <Wrapped
          {...props}
          show={show}
          onToggle={toogleHandler}
          onHide={hideHandler}
        />
      ));
});

它是Dropdown按钮的装饰器

  // hideHandler caller
        class Foo extends Component {
            constructor(props) {
              super(props);
              this.refButton.bind(this);
              this.documentClick$ = Observable.fromEvent(global.document, 'click')
                .filter(event => this.button !== event.target)
                .do((event) => { this.props.onHide(event); });
            }

            componentDidMount() {
              this.documentClick$.subscribe();
            }
            componentWillUnmount() {
              this.documentClick$.unsubscribe();
            }
            refButton = (ref) => {
              this.button = ref;
            }
        }

1 个答案:

答案 0 :(得分:3)

你可以通过将toggle $ / hide $映射到前一个状态的函数来实现没有条件的show $:

const show$ = Observable.merge(
    toggle$.mapTo(prev => !prev),
    hide$.mapTo(prev => false))
        .startWith(false)
        .scan((state, changeState) => changeState(state));

您可以做的另一项改进是使用可切换的实现。您可以使用重构mapPropsStream

,而不是使用重构componentFromStream
export const toggleable = mapPropsStream(props$ => {
    const { handler: toogleHandler, stream: toogle$ } = createEventHandler();
    const { handler: hideHandler, stream: hide$ } = createEventHandler();
    const show$ = Observable.merge(
        toggle$.map(() => prev => !prev),
        hide$.map(() => prev => false))
            .startWith(false)
            .scan((state, changeState) => changeState(state));

    return props$
        .combineLatest(
            show$,
            (props, show) => ({
                ...props,
                show
                onToggle: toogleHandler
                onHide: hideHandler
            })
        );
});