将 View 连接到持续分派(dispatch)事件的库的最佳方法是什么?我在 redux 真实示例中看到,最好使用 mapDispatchToProps 并注入(inject)您的加载操作。在我们的例子中,我们需要监听事件以随时间调度。我认为我们可以使用中间件来做到这一点,但我不是 100% 确定。还有另一种选择是在 Action 创建者本身内部进行监听。
有什么想法吗?
//应用程序.jsx
<div>
<MyCollection name="ONE" />
<MyCollection name="TWO" />
</div>
//我的集合.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);
// Action .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
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;
}
}
//中间件.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是您正在寻找的,以防您不想使用自制中间件使您的应用过于复杂。
关于javascript - 将 react-redux 与基于事件的第 3 方库一起使用的最佳方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36756239/