我正在为我的 ReactJS 项目使用 ALT。如果 ajax 调用尚未完成并且我切换到另一个页面,我会收到无法"dispatch"错误。
大多数情况下,这就是我的项目的设置方式。我有 Action 、商店和组件。我在服务器上查询 componentDidMount
生命周期。
行动:
import alt from '../altInstance'
import request from 'superagent'
import config from '../config'
import Session from '../services/Session'
class EventActions {
findNear(where) {
if (!Session.isLoggedIn()) return
let user = Session.currentUser();
request
.get(config.api.baseURL + config.api.eventPath)
.query(where)
.set('Authorization', 'Token token=' + user.auth_token)
.end((err, res) => {
if (res.body.success) {
this.dispatch(res.body.data.events)
}
});
}
}
export default alt.createActions(EventActions)
商店
import alt from '../altInstance'
import EventActions from '../actions/EventActions'
class EventStore {
constructor() {
this.events = {};
this.rsvp = {};
this.bindListeners({
findNear: EventActions.findNear
});
}
findNear(events) {
this.events = events
}
}
export default alt.createStore(EventStore, 'EventStore')
组件
import React from 'react';
import EventActions from '../../actions/EventActions';
import EventStore from '../../stores/EventStore';
import EventTable from './tables/EventTable'
export default class EventsPage extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
events: [],
page: 1,
per: 50
}
}
componentDidMount() {
EventStore.listen(this._onChange.bind(this));
EventActions.findNear({page: this.state.page, per: this.state.per});
}
componentWillUnmount() {
EventStore.unlisten(this._onChange);
}
_onChange(state) {
if (state.events) {
this.state.loading = false;
this.setState(state);
}
}
render() {
if (this.state.loading) {
return <div className="progress">
<div className="indeterminate"></div>
</div>
} else {
return <div className="row">
<div className="col m12">
<h3 className="section-title">Events</h3>
<UserEventTable events={this.state.events}/>
</div>
</div>
}
}
}
最佳答案
componentDidMount() {
EventStore.listen(this._onChange.bind(this));
EventActions.findNear({page: this.state.page, per: this.state.per});
}
这是我的猜测。您正在绑定(bind) onChange ,这将触发 _onChange 中的 setState ,并且还会从 findNear 触发一个操作(由于调度)。因此,可能存在两者同时更新的时刻。
首先,我认为findNear应该在componentDidMount中排在第一位。
并且还尝试将其分成两个不同的 WebView (哑 View 和逻辑 View ,其中第一个仅显示数据,而另一个将执行例如获取操作)。另外一个好主意是使用 AltContainer 实际上避免 _onChange 操作,这是非常无用的,因为 AltContainer “内部”有类似的东西。
constructor() {
this.events = {};
this.rsvp = {};
this.bindListeners({
findNear: EventActions.findNear
});
}
findNear(events) {
this.events = events
}
我也会重构这个
constructor() {
this.events = {};
this.rsvp = {};
}
onFindNear(events) {
this.events = events
}
Alt 有非常好的东西,例如自动解析器,它将查找操作名称 + on,因此如果您有名为 findNear 的操作,它将搜索 onFindNear。
关于reactjs - 不变违规 : Dispatch. 调度(...):无法在调度中间调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36399419/