【发布时间】:2018-09-21 08:44:08
【问题描述】:
我在 ReactJS 中使用 Dispatcher 时遇到了一些问题。因此,我尝试从商店中删除此调度程序,但商店仍然运行良好。正确存储我的数据并且更改事件运行良好。
现在我在我们的应用程序中使用调度程序有点困惑。
这里是代码
MenuList 是我的组件,我在其中调用MenuStore.getMenuFromAPI(),之后我还添加了MenuStore 的onChange 事件。
class MenuList extends React.Component{
constructor(){
super();
this.state = {open:false, menuList:"",numbering:-1}
}
componentWillMount(){
var that = this;
MenuStore.getMenuFromAPI();
MenuStore.on("change", ()=> {
that.setState({menuList:MenuStore.getMenu()});
})
}
componentWillReceiveProps(nextProps){
if(nextProps.show!=this.props.show){
this.setState({open:nextProps.show});
}
}
render(){
const { classes } = this.props;
return (
<div>My MEnu</div>
)
}
}
菜单商店
class MenuStore extends EventEmitter {
constructor() {
super();
this.menu = null;
}
getMenu(){
return this.menu;
}
getMenuFromAPI(){
var that = this;
$.ajax({
type: "POST",
url: LinkConstants.GETMENU,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data: "",
dataType :"json",
success: function(response) {
that.menu =response;
that.emit("change");
}.bind(this),
error: function(xhr, status, err) {
console.log(err);
}.bind(this)
});
}
// handleAction(action) {
// switch (action.type) {
// case ActionTypes.MENU: {
// this.getMenuFromAPI();
// break;
// }
// }
// }
}
const menuStore = new MenuStore;
//Dispatcher.register(menuStore.handleAction.bind(menuStore));
export default menuStore;
如您所见,我注释掉了 Dispatcher.register 行和 handleAction 函数。
上面的代码可以正常工作,但我想知道为什么在这里使用 Dispatcher?
如果我只想将我的数据存储在 MenuStore 中并从应用程序中任何组件上的 MenuStore 取回它。因此有必要使用调度程序和操作,或者只使用商店。
请通过适当的示例或案例场景(如果可能)澄清我的疑问,何时使用调度程序和操作或何时仅使用商店。
【问题讨论】:
标签: reactjs react-redux reactjs-flux refluxjs