Flux,如何正确复用组件?

Flux, how to correctly reuse components?

仍在研究 Flux,我对商店的一些逻辑感到困惑。 假设我创建了一个组件,一个管理投票的按钮,就像一个开关 "Yes"/"No".

所以我的 voteButton 管理一个 voteAction,它使用 Dispatcher 调用一个 Store 函数来改变 votedByViewer 状态。

一切都很有趣,一切都很好...如果我只有一个按钮。 但是如果我有倍数,它们共享同一个商店,所以重新渲染发生在所有倍数组件上。

这是我的初始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;

知道如何解决吗?也许我必须使用容器? 谢谢

您只需为您使用的每个按钮设置一个 ID。当您单击时,它会将此 ID 传递给操作,然后是调度程序,然后是商店接收它。 您的商店是一个数组,每个键都是一个按钮 ID。当商店收到数据时,它会更改所需的 ID。并且您的按钮获得其 ID 的状态(getVote('buttonid');)