【发布时间】:2017-04-16 09:47:49
【问题描述】:
好的。我有点新反应,我有一个#1市长问题。真的找不到任何解决方案。
我已经构建了一个呈现对象列表的应用程序。该列表目前来自我的模拟 API。对象列表存储在存储中。获取对象的存储操作由组件完成。
我的问题是在显示这些对象时。当用户单击显示时,它会呈现一个包含对象详细信息的页面。存储方面,这意味着触发一个 getSpecific 函数,该函数根据 ID 从存储中检索对象。
这一切都很好,商店仍然有物品。直到我重新加载页面。那就是当商店被擦除时,会创建一个新实例(这是我的猜测)。商店现在是空的,现在不可能获得那个特定的对象(在我当前的实现中)。
所以,我在某处读到这是设计使然。解决方案是:
- 将存储保存在本地存储中,以保留数据?
- 再次调用 API 并再次获取所有对象?
在情况 2 中,这应该在何时/何地发生?
商店应该如何确保它始终拥有预期的数据? 有什么提示吗?
一些如果实现:
//List.js
componentDidMount() {
//The fetch offers function will trigger a change event
//which will trigger the listener in componentWillMount
OfferActions.fetchOffers();
}
componentWillMount() {
//Listen for changes in the store
offerStore.addChangeListener(this.retriveOffers);
}
retrieveOffers() {
this.setState({
offers: offerStore.getAll()
});
}
.
//OfferActions.js
fetchOffers(){
let url = 'http://localhost:3001/offers';
axios.get(url).then(function (data) {
dispatch({
actionType: OfferConstants.RECIVE_OFFERS,
payload: data.data
});
});
}
.
//OfferStore.js
var _offers = [];
receiveOffers(payload) {
_offers = payload || [];
this.emitChange();
}
handleActions(action) {
switch (action.actionType) {
case OfferConstants.RECIVE_OFFERS:
{
this.receiveOffers(action.payload);
}
}
}
getAll() {
return _offers;
}
getOffer(requested_id) {
var result = this.getAll().filter(function (offer) {
return offer.id == requested_id;
});
}
.
//Show.js
componentWillMount() {
this.state = {
offer: offerStore.getOffer(this.props.params.id)
};
}
【问题讨论】:
标签: reactjs flux reactjs-flux