我正在尝试使用 redux 切换(显示/隐藏(反应组件,但出现错误:
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 切换组件,因为我想添加更多可以切换的组件。
你的化简器不是一个数组,所以它会中断。
如果你把减速器换成这个,它能工作吗?
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;
}
};
和您的切换组件:
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;
};
您的状态没有任何名为toggles
的属性,而是将切换状态直接保留在对象state
作为键/值。
所以改变
const show = useSelector(state => state.toggles[id]);
自
const show = useSelector(state => state[id]);