【问题标题】:Redux architecture confuse about initial store stateRedux 架构对初始存储状态感到困惑
【发布时间】:2016-08-22 06:01:52
【问题描述】:

全部:

我对 React 和 Redux 还是很陌生。目前我想建立一个标题菜单,其中包含几个菜单项,如下所示:

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

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

对此的任何示例将不胜感激。

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    您不应该将 redux 存储用于琐碎的事情,例如项目的高亮状态。这样想。您的商店用于存储来自服务器的数据。组件上发生变化的小东西,例如颜色或类名,应该在组件的状态下处理。

    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% :)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 2014-10-03
    • 2016-08-14
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    相关资源
    最近更新 更多