模态和通知是附加到正文的组件。因此它们与普通组件的工作差别不大。在我的应用程序中,我可以想到实现它们的两种方法,我不确定哪种方法更好。
在这种方法中,我创建了一个具有create方法的NotificationHelper类。在其中,我创建一个新的容器节点,将其附加到正文,然后调用React.render(,容器);
因此任何组件都可以调用NotificationHelper.create()并创建通知。通知组件管理它的生命周期,并在计时器到期或有人点击关闭按钮时关闭。
问题往往是,我需要在页面上显示响应XHR响应(成功或失败)的通知,所以在我的actionCreator中,我将有这样的代码
APIManager.post(url, postData).then(function(response) {
NotificationHelper.create(<SuccessNotification />)
});
我不知道从渲染新组件的动作创建者那里调用这样的东西是否正确。
另一种方法是创建NotificationStore并在emitChange上呈现通知组件。 代码看起来像这样
在我的App.js中,代码将是
<body>
<Header />
<Fooder />
<NotificationContainer />
</body>
然后在NotificationContainer中,我会做类似
的事情onChange: function() {
this.setState({customNotification: NotificationStore.get()});
},
render: function() {
<Notification>
{this.state.customNotification}
</Notification>
}
最后,动作创建者看起来像
Dispatcher.dispatch({
actionType: 'notification',
component: <MyComponent/>
});
这种方法的问题是商店的额外开销。商店在这里没有做任何有意义的事情,只是为了追随变化。从动作创建者,我们将数据传递到商店,组件再次从商店获取相同的数据并进行渲染。所以我们完成了通量循环而没有真正从中获得任何东西。
另外,我现在需要在我的应用程序开始时初始化NotificationContainer,即使此时我没有任何通知。
答案 0 :(得分:1)
我真的不明白你的问题是怎样的问题。它确实完成了它应该做的事情,如果你以后需要在它上面构建它,你可以很容易地做到这一点。在我看来,通知和其他非真实组件所有者功能是使用助焊剂的最佳理由之一(90%的时间我不建议使用助焊剂)。
使用flux,通知操作创建者将负责在设定的一段时间后创建删除通知操作。您还可以在通知上有一个 x 按钮,单击该按钮会创建该操作,然后这些按钮将转到存储区域,如果该项目存在,则会删除该项目,以及依赖于此商店更新的任何/所有视图。当我说任何/所有我的意思是通知组件可能被隐藏,或者可能有另一种方法来查看应用程序的一个页面上的通知,或者可能有一个简单的计数器,其中包含应用程序中任何位置的通知数量。
附注:不要以可以多次渲染的方式传递元素。如果您需要提前指定组件,请通过{component: SuccessNotification, props: props}
。
答案 1 :(得分:0)
I follow the answer of FakeRainBrigand.
Sorry the self promotion here but I created a Notification component that you can use with Flux. Here you can see a issue that shows a example of usage with Alt, but the principles are the same. You add the component to a top level element on your HTML and subscribe that component to a Notification store. On your notification action creator, you can add notification with some properties like: level, position, auto-dismissible, action, etc.