Redux架构混淆了初始存储状态

时间:2016-04-27 18:42:19

标签: reactjs redux

所有

我是React和Redux的新手。目前我想构建一个包含多个菜单项的标题菜单,如下所示:

enter image description here

  

每个项目都可以单击并突出显示(只需使用相同的颜色突出显示),点击操作将切换该项目的突出显示。

我尝试遵循redux的模式,这会保存商店中每个项目的状态(这是第一个让我感到困惑的地方,我不确定是否应该在组件中保存此突出显示状态,以便它用户指定初始高亮状态更容易,或者在全局存储中,因此我可以在任何地方同步)。但我不知道如何为此设计数据结构,尤其是当它允许用户在JSX中指定项目初始状态时(例如<MenuItem highlight={true} />

任何有关此的例子都将受到赞赏。

1 个答案:

答案 0 :(得分:2)

你不应该使用redux商店来处理像项目的突出显示状态之类的微不足道的事情。这样想吧。您的商店用于存储来自服务器的数据。应该在组件的状态下处理组件上变化的小事物,如颜色或className。

class MyComponent extends React.Component {
    constructor(){
        super();
        this.state = {highlighted: 1};
        this.handleHighlightClick = this.handleHighlightClick.bind(this);
    }
    handleHighlightClick(e, val){
        //set state here for your highlight
        e.preventDefault();
        this.setState({highlighted: val})
    }
    render(){
        // for the sake of this example i'll just show a list of items to render
        let menuItems = [{color: 'red'},{color: 'orange'},{color: 'yellow'},{color: 'white'}];
        return (
            {menuItems.map((data, key) => 
                <MenuItem 
                  data={data} // data is the color object from the list
                  highlighted={key===this.state.highlighted} // the key of which one is highlighted gets stored in local state
                  onClick={(e) => { this.handleHighlightClick(e, key)} } /> // inline function to pass through the key of the exact menu item so that you can save its key to state
            )}
        );
    }
}

现在这只是一个简单的例子,并不涵盖您要做的所有事情。但它约占你想做的90%,所以我会让你完成最后的10%:)

相关问题