我正在尝试使用redux切换(显示/隐藏)react组件,但出现错误:
Error: An error occurred while selecting the store state.
当我通过直接调用访问状态时,此错误消失。
更改此内容:
const show = useSelector(state => state.toggle[id]);
对此:
const show = useSelector(state => state.empty);
import React from 'react';
import {useSelector} from 'react-redux';
export const Toggle = ({id, children}) => {
const show = useSelector(state => state.toggles[id]);
return show ? children : null;
};
const initialState = {
empty: false
};
export default (state = initialState, action) => {
switch (action.type) {
case 'SHOW':
return {...state, [action.payload]: true};
case 'HIDE':
return {...state, [action.payload]: false};
default:
return state;
}
};
export const showToggle = id => ({type: 'SHOW', payload: id});
export const hideToggle = id => ({type: 'HIDE', payload: id});
import React from 'react';
export const MyComponent = ({onClick}) => {
return (
<div>
Do something awesome here
<button onClick={onClick}>Ok</button>
</div>
)
};
import React from 'react';
import {useDispatch} from 'react-redux';
import {Toggle} from './Toggle';
import {MyComponent} from './MyComponent';
import {showToggle, hideToggle} from './actions';
export const SomeOtherComponent = () => {
const dispatch = useDispatch();
const toggleId = 'empty';
return (
<div>
<span>Say something<span>
<Toggle id={toggleId}>
<MyComponent onClick={() => dispatch(hideToggle(toggleId))}/>
</Toggle>
<button onClick={() => dispatch(showToggle(toggleId))}>Show my component</button>
</div>
)};
基本上,我想按ID切换组件,因为我想添加更多可以切换的组件。
答案 0 :(得分:1)
您的reducer不是数组,因此会损坏。
如果您将减速器更改为此有效吗?
const initialState = [];
export default (state = initialState, action) => {
switch (action.type) {
case 'SHOW':
return {...state, [action.payload]: true};
case 'HIDE':
return {...state, [action.payload]: false};
default:
return state;
}
};
和您的Toggle组件:
import React from 'react';
import {useSelector} from 'react-redux';
export const Toggle = ({id, children}) => {
const show = useSelector(state => state[id]);
return show ? children : null;
};
替代:
const initialState = {
show_list: [],
// other state keys
};
export default (state = initialState, action) => {
switch (action.type) {
case 'SHOW':
let show_list = state.show_list;
show_list[action.payload] = true;
return {...state, show_list};
case 'HIDE':
let show_list = state.show_list;
show_list[action.payload] = false;
return {...state, show_list};
default:
return state;
}
};
切换组件:
import React from 'react';
import {useSelector} from 'react-redux';
export const Toggle = ({id, children}) => {
const show = useSelector(state => state.show_list[id]);
return show ? children : null;
};
答案 1 :(得分:0)
您的状态没有名为toggles
的任何属性,而是直接将切换状态保留在state
对象中作为键/值。
所以改变
const show = useSelector(state => state.toggles[id]);
到
const show = useSelector(state => state[id]);