【发布时间】:2018-04-18 09:00:24
【问题描述】:
我已经尝试将 store 挂接到通过 React.createClass 定义的 react 组件中。我已经实现了全局状态,但需要进行大量重构。
我将分享相关代码并在之后继续提问。
动作
var Reflux = require('reflux');
module.exports = Reflux.createActions(['markAllRead']);
商店
var Reflux = require('reflux');
var StoreActions = require('../actions/storeActions/notifications');
var React = require('react');
module.exports = Reflux.createStore({
init: function(){
this.listen(StoreActions.markAllRead, this.markAllRead);
this.state = {
unreadCount: 5
};
},
markAllRead(count){
this.state = {
unreadCount: 1
};
this.trigger(this.state);
}
});
标题组件
var notificationsStore = require('../stores/notifications');
getInitialState: function() {
// this.state = {}; // our store will add its own state to the component's
// this.store = notificationsStore; // <- just assign the store class itself
return {
notificationsData: this.props.notificationsData,
state: {},
store: notificationsStore
};
},
内部渲染函数
<div onClick={this.toggleNotifications} className='bell' id='bell'>
<Glyphicon glyph='bell' id='bell'></Glyphicon>
{
this.state.store.state.unreadCount > 0 ?
<span className='notBadge' id='bell'><span id='bell'>{this.state.store.state.unreadCount}</span></span>
: null
}
</div>
<div id='notificationsPanel' className='notificationsPanel'>
<NotificationsList list={this.state.notificationsData.notifications} clickHandler={this.clickHandler}/>
<div className='footer notification_bar'>
<span className='pull-left'><a onClick={this.seeAll}>See all</a></span>
<span className='pull-right'><a onClick={this.markAllRead}>Mark all as read</a></span>
</div>
</div>
... ...
updateReadStatus: function(){
notificationsStore.markAllRead();
},
markAllRead: function(){
ActionsNotifications.markAllRead().then(this.updateReadStatus); // API call
},
在函数updateReadStatus 中,我手动调用了存储方法(markAllRead)。当我已经在商店里听它们时,触发动作的正确方法是什么?
其次,我目前收到的商店状态为this.state.store.state.someVariable。我怎样才能在getInitialState 或任何其他功能中让生活变得简单,只需要做this.state.someVariable? getInitialState 中注释的行在 constructor(){} 中很有用,但在我的 createClass() 设置中却没有
谢谢!
【问题讨论】: