简体   繁体   English

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

[英]What's the best way to use react-redux with event based 3rd party library

What is the best way to wire up a view to a library which continually dispatches events? 将视图连接到不断调度事件的库的最佳方法是什么? I saw in the redux real-world example that it's best to use mapDispatchToProps and inject your loading action. 我在redux实际示例中看到,最好使用mapDispatchToProps并注入加载操作。 In our case we need to listen for events to dispatch over time. 在我们的案例中,我们需要监听随时间推移的事件。 I thought we could use middleware to do this but I'm not 100% sure. 我以为我们可以使用中间件来做到这一点,但我不是百分百肯定。 There other alternative would be to do the listening inside the action creator itself. 还有其他选择是在动作创建者本身内进行聆听。

Any ideas? 有任何想法吗?

// app.jsx // app.jsx

<div>
  <MyCollection name="ONE" />
  <MyCollection name="TWO" />
</div>

// my-collection.jsx // my-collection.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);

// actions.js // actions.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
  }
}

// reducer.js // reducer.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;
  }
}

// middleware.js // middleware.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'});    
    }
  }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM