将react-redux与基于事件的第三方库结合使用的最佳方式是什么

cam*_*est 5 javascript reactjs redux react-redux

将视图连接到持续调度事件的库的最佳方法是什么?我在 redux 真实世界示例中看到,最好使用 mapDispatchToProps 并注入加载操作。在我们的例子中,我们需要监听随时间调度的事件。我认为我们可以使用中间件来做到这一点,但我不是 100% 确定。还有另一种选择是在动作创建者本身内部进行监听。

有任何想法吗?

// 应用程序.jsx

<div>
  <MyCollection name="ONE" />
  <MyCollection name="TWO" />
</div>
Run Code Online (Sandbox Code Playgroud)

// 我的集合.jsx

import {load} from './actions';

class MyCollection extends React.Component {
  componentDidMount() {
    this.props.load(this.props.name);
  }

  componentDidUpdate(prevProps) {
    if(prevProps.name !== this.props.name) {
      this.props.load(this.props.name);
    }
  }

  render() {
    return (
      <div>{this.props.name}: {this.props.value}</div>
    )
  }
}

function mapStateToProps(state) {
  return {
    value: state.value
  }
}

const mapDispatchToProps = {
  loadAndWatch
}

connect(mapStateToProps, mapDispatchToProps)(MyCollection);
Run Code Online (Sandbox Code Playgroud)

// 动作.js

import {MyCollection} from '@corp/library';

export function load(name) {
  return (dispatch, getState) => {
    MyCollection.getValue(name, value => {
      dispatch(setValue(name));
    })
  }
}

export function setValue(name) {
  return {
    type: 'SET_VALUE',
    name
  }
}
Run Code Online (Sandbox Code Playgroud)

// 减速器.js

function reducer(state, action) {
  switch(action.type) {
    case 'SET_WATCHING':
      return Object.assign({}, state, {isWatching: true});
    case 'SET_VALUE':
      return Object.assign({}, state, {value: action.value});
    default:
      return state;
  }
}
Run Code Online (Sandbox Code Playgroud)

// 中间件.js

import {setValue} from './actions';

function middleware({dispatch, getState}) {
  return next => action => {
    switch (action.type) {
      case 'SET_VALUE':
        next(action);

        if (getState().isWatching) {
          return;
        }

        MyCollection.addChangeListener(name, value => {
          dispatch(setValue(name))
        });

        dispatch({type: 'SET_WATCHING'});    
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Raf*_*lis 0

我相信redux-observable就是您正在寻找的,以防您不想使用自制的中间件使您的应用程序过于复杂。