[英]How can it possible to share different state on different multiple Components in React-Redux
I have Menu
and MenuItem
react components. 我有Menu
和MenuItem
反应组件。
They works like this. 他们这样工作。
<Menu openOnClick>
<MenuItem target="/" text="Item 1" active />
<MenuItem target="#" text="Item 2" parent>
<MenuItem target="/" text="Item 3" />
<MenuItem target="/" text="Item 4" />
</MenuItem>
</Menu>
<Menu>
<MenuItem target="/" text="Item 1" active />
<MenuItem target="#" text="Item 2" parent>
<MenuItem target="/" text="Item 3" />
<MenuItem target="/" text="Item 4" />
</MenuItem>
</Menu>
Normally MenuItem
opens as dowpdown when mouse over but I want to provide also click mode for dropdown. 通常,当鼠标悬停时, MenuItem
打开,但我想提供下拉菜单的点击模式。
clickMode illustrate clickMode说明
So MenuItem
has clickMode
state.I want to this if Menu
(parent component) has openOnClick
prop true (given by user) then MenuItem
clickMode
state should be true. 所以MenuItem
有clickMode
状态。如果Menu
(父组件)有openOnClick
prop true(由用户给出),我希望这样,那么MenuItem
clickMode
状态应为true。
I am achiving this in MenuItem component with redux. 我在使用redux的MenuItem组件中实现了这一点。
const mapStateToProps = (state) => {
console.log(state.menuReducer.clickMode)
return {
clickMode:state.menuReducer.clickMode
}
}
But if there are multiple Menu
component it doesn't work.Because redux
store change every dispatch event. 但是如果有多个Menu
组件则不起作用。因为redux
store会更改每个dispatch事件。
Here is redux state logs. 这是redux状态日志。
Here is Menu
reducer. 这是Menu
reducer。
export const menuReducer = (state = [], action) => {
switch (action.type) {
case menuConstants.CLICK_MODE:
return {
type: menuConstants.CLICK_MODE,
clickMode: action.clickMode
}
default:
return state;
}
}
How can handle this? 怎么办呢?
Many thanks for help. 非常感谢您的帮助。
To do that you can add a high level more of abstraction. 要做到这一点,你可以添加更高级别的抽象。 I think in your store you have somethig like: 我认为在你的商店你有一些喜欢:
const state: State = { menu:[ { //menuItem }, { //menuItem } . . . ] }
I think you need to do somethink like that: 我想你需要做那样的事情:
const state: State = { menus: [ { menu:[ { //menuItem }, { //menuItem } . . . ] } ... ] }
Currently you are storing a boolean in your state, I would suggest to introduce for every Menu a key ( react already asked you to do it anyway ) and in the handler to dispatch it. 目前你正在你的状态中存储一个布尔值,我建议为每个菜单引入一个键(反应已经要求你完成它)并在处理程序中调度它。
so your action would look something like this: 所以你的行动看起来像这样:
const openOnClick = (id) => ({
type: "CLICK_MODE",
id: id
})
and your reducer: 和你的减速机:
const initialState = {
activeMenues: []
}
function reducer(state = initialState, action) {
switch(action.type) {
case "CLICK_MODE": return {
...state,
activeMenues: [...this.state.activeMenues, action.id]
}
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.