【发布时间】:2016-02-01 14:22:25
【问题描述】:
仍在研究 Flux,我对商店的一些逻辑感到困惑。 假设我创建了一个组件,一个管理投票的单个按钮,例如“是”/“否”开关。
所以我有我的 voteButton 来管理一个 voteAction,它使用一个 Dispatcher 来调用一个改变 votedByViewer 状态的 Store 函数。
一切都很有趣,一切都很好……如果我只有一个按钮。 但如果我有多个,它们共享同一个商店,因此重新渲染会发生在所有多个组件上。
这是我最初的js:
// Parse all DIV for React management
$("#be-content [id*=like]").each(function (index) {
var div_id = $(this).attr("id");
// Render the VoteButton
ReactDOM.render(
<VoteButton />,
document.getElementById(div_id)
)
});
每个 VoteButton 都在页面中正确呈现,但每个开关都会更改所有按钮的状态。这是我的投票按钮:
var voteStore = require('../stores/voteStore') ;
var voteActions = require('../actions/voteActions');
var VoteButton = React.createClass({
getInitialState: function () {
return {
voted: voteStore.getVote()
}
},
componentDidMount: function () {
voteStore.addVoteListener(this._onChange);
},
componentWillUnmount: function () {
voteStore.removeVoteListener(this._onChange);
},
handleVote: function () {
this.state.voted ? voteActions.unvote() : voteActions.vote()
},
_onChange: function () {
this.setState({
voted: voteStore.getVote()
})
},
render: function () {
return (
<div className="link">
<button onClick={this.handleVote}>{this.state.voted? 'YES':'NO'}</button>
</div>
)
}
});
module.exports = VoteButton;
知道如何解决它吗?也许我必须使用容器? 谢谢
【问题讨论】:
标签: reactjs reactjs-flux flux