[英]React and Flux - how to tie view to store data
我開始學習Flux的React,遇到了一些麻煩。
我有一個商店和兩個視圖(組件),當商店數據發生更改時,我想更新一個視圖,但是我不確定如何將兩者結合在一起。
這是怎么回事:
我單擊視圖1中的按鈕,這將修改存儲中的數據,然后應更新視圖2。
view1 onClick =>調度操作=>修改商店數據=>更新view2
除了最后一部分,我擁有一切,在對商店進行更改時將視圖和商店聯系在一起。 當前所做的只是修改一個類名,但是稍后我會看到其他功能。
所以我的問題是,如何將商店與視圖狀態綁定?
view2(主頁)
var React = require('react');
var DefaultLayout = React.createFactory(require('../layouts/Default'));
var ReactGridLayout = React.createFactory(require('react-grid-layout'));
var desktopStore = require("../stores/DesktopStore");
// var classNames = require('classnames');
var HomePage = React.createClass({
displayName: 'Index.jsx',
getInitialState: function(){
return {zoomed: desktopStore.get('zoom')};
},
getDefaultProps: function() {
return {
layout: DefaultLayout
};
},
render: function() {
var parentClassString = "desktop"; // base class
if(this.state.zoomed){
parentClassString += " zoomed"; // add a class based on the zoomed property
}
return (
<div className={parentClassString}>
<ReactGridLayout className="layout" cols={80} rowHeight={30} verticalCompact={false}
initialWidth={10} autoSize={false} isResizable={false}>
<div key={1} _grid={{x: 0, y: 0, w: 1, h: 1}} >1</div>
<div key={2} _grid={{x: 0, y: 0, w: 1, h: 1}} >2</div>
<div key={3} _grid={{x: 0, y: 0, w: 1, h: 1}} >3</div>
<div key={4} _grid={{x: 0, y: 0, w: 1, h: 1}} >4</div>
<div key={5} _grid={{x: 0, y: 0, w: 1, h: 1}} >5</div>
<div key={6} _grid={{x: 0, y: 0, w: 1, h: 1}} >6</div>
</ReactGridLayout>
</div>
);
}
});
module.exports = HomePage;
View1(標題)
var _name = 'TopHeader.jsx';
var React = require('react');
var DesktopApi = require('../utilities/DesktopApi');
var TopHeader = React.createClass({
displayName: _name,
handleClick: function(){
DesktopApi.toggleZoom(); // this goes to the dispatcher and emits a change to update the desktopStore
},
render() {
return (
<div className="top-header">
<span>Header</span>
<span className="plus" onClick={this.handleClick}> [+] </span>
</div>
);
}
});
module.exports = TopHeader;
官方的Facebook指南在這里提供了幫助,我可以使用componentDidMount創建偵聽器,並使用componentWillUnmount刪除它們
componentDidMount: function() {
desktopStore.addChangeListener(this._onChange);
},
componentWillUnmount: function() {
desktopStore.removeChangeListener(this._onChange);
},
_onChange: function(){
this.setState({zoom: true});
}
如果您想創建一個mixin來將視圖綁定到商店,則可以閱讀fluxxor的源代碼。 這是storeWatchMixin的示例。 或者,您可以使用高階組件來包裝組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.