flux: view doesn't refresh after store update

时间:2017-03-22 18:47:27

标签: javascript reactjs flux

I study FLUX and try to write simple example on it. It is about a menu where I can select every single item (it is marked by (*)). So, here is main excerpts of the code:

AppContainer.js:

class AppContainer extends React.Component 
{ 
    static getStores() { 
        return [MenuStore]; 
    } 
    static calculateState(prevState) { 
        return { 
            menu: MenuStore.getState(),
            onclick: Actions.onclick
        }; 
    }
    render() {
        return <MenuView onclick={this.state.onclick} menu={this.state.menu.get('list')} cur={this.state.menu.get('cur')} />;
    } 
} 

MenuStore.js

class MenuStore extends ReduceStore{
    constructor() {
        super(MenuDispatcher);
    }
    getInitialState() {
        // return {list: ["About", "Contacts", "Price", "Home"], cur: 0};
        return Immutable.Map({list: ["About", "Contacts", "Price", "Home"], cur: 2});
    }

    reduce(state, action) {
        switch (action.type) {
            case ActionTypes.ON_CLICK:
                console.log('MenuStone ON_CLICK');
                state.cur = action.index;
                return state;
            default:
                return state;
        }
    }
}

MenuView.js:

class MenuView extends React.Component{

    constructor(props){
        super(props);
    }
    render(){
        return <ui>{this.props.menu.map((menu, index) => {
                var active = (this.props.cur === index) ? true : false;
                return <MenuItem onclick={this.props.onclick} key={index} index={index} active={active} label={menu} />;
            })}</ui>;
    }
}

class MenuItem extends React.Component {
    constructor(props) {
        super(props);

        this.state = {label: props.label};
        this.click = this.click.bind(this);
    }

    click(index) {
        console.log('MenuItem click');
        this.props.onclick(this.props.index);
    }

    render() {
        var mark = '';
        if (this.props.active)
            mark = '(*) ';
        return <li onClick={this.click}>{mark}{this.state.label}</li>;
    }
}

Actions.js:

const Actions = {
    onclick(index) {
        console.log('Actions.onclick');
        MenuDispatcher.dispatch({
            type: ActionTypes.ON_CLICK,
            index,
        });
    }
};

When I run the code, it is work fine until I click a menu item. The code state.cur = action.index; executes, but nothing changes on the page.

What should I do to update the views?

0 个答案:

没有答案