5

我正在尝试对以下 React-Reflux 代码进行 es6 化:

var TimeStore = Reflux.createStore({
    listenables: [TimeActions],

    onTick: function(tick) {
        ....    
    }
})

var Watch = React.createClass({
    mixins: [Reflux.connect(TimeStore, 'tick')],
    ...

资源

我不确定如何使用react-decorator进行转换。这就是我将其转换为:

const SomeDecorator = MixinDecorator(
    'TimerActions',  // displayName
    Reflux.connect(TimeStore, 'tick')
);

@SomeDecorator
class Watch extends React.Component {
    ...

它使用 babel 编译(stage设置为0),但效果不佳。任何建议如何解决这个问题?另外,是否可以 es6-ify 商店?

4

2 回答 2

8

完全跳过 mixins。

    class AppCtrlRender extends Component {
        binder(...methods) { methods.forEach( (method) => this[method] = this[method].bind(this) ); }

        render() {
            var data = this.state.Data;
            data = JSON.stringify(data, null, 2);
            var data2 = this.state.Data2;
            data2 = JSON.stringify(data2, null, 2);
            var data3 = this.state.Data3;
            data3 = JSON.stringify(data3, null, 2);
            return (
                <div id='AppCtrlSty' style={AppCtrlSty}>
                    React 1.3 ReFlux with WebSocket<br/><br/>
                    {data}<br/><br/>
                    Data2: {data2}<br/><br/>
                    Data3: {data3}<br/><br/>
                </div>
            );
        }
    }

    function getState() {
        return {
            Data: BasicStore.getData(),
            Data2: BasicStore.getData2(),
            Data3: BasicStore.getData3()
        };
    };

    export default class AppCtrl extends AppCtrlRender {
        constructor() {
            super();
            this.state = getState();
            this.binder('storeDidChange');
        }

        componentDidMount() { this.unsubscribe = BasicStore.listen(this.storeDidChange); }
        componentWillUnmount() { this.unsubscribe(); }
        storeDidChange() { this.setState(getState()); }
    }
于 2015-09-04T19:47:46.030 回答
2

新 Reflux ES6 API 的 OP 中代码的正确翻译如下所示:

var TimeActions = Reflux.createActions(['tick']);

class TimeStore extends Reflux.Store
{
    constructor()
    {
        super();
        this.listenables = TimeActions;

        // whatever state you want to store should
        // now be on a state property in the store
        this.state = { ticks: 0 };
    }

    onTick(tick)
    {
        // now update values in your store via setState
        this.setState({ ticks: this.state.ticks+1 });
    }
}

class Watch extends Reflux.Component
{
    constructor(props)
    {
        super(props);

        // set this.store to the store class itself
        this.store = TimeStore;
    }

    render()
    {
        // from now any any changes to the store will automatically
        // reflect in your component's state.
        return <p>{this.state.ticks} ticks...</p>;
    }
}

一个工作的 JSFiddle 在这里:https ://jsfiddle.net/uomkhbzj/

API 的文档在这里:https ://github.com/reflux/refluxjs#react-es6-usage

于 2016-07-15T01:45:19.877 回答