使用Redux切换主题不起作用



这是我的configureStore.js文件

import {createStore, applyMiddleware, compose, combineReducers} from 'redux';
import thunk from 'redux-thunk';
import {persistStore, persistReducer} from 'redux-persist';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {stateReducer, themeReducer, authReducer} from './index';
const persistConfig = {
key: 'root',
storage: AsyncStorage,
whitelist: ['themeReducer'],
};
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const rootReducer = combineReducers({stateReducer, themeReducer, authReducer});
const persistedReducer = persistReducer(persistConfig, rootReducer);
export default () => {
let store = createStore(
persistedReducer,
composeEnhancer(applyMiddleware(thunk)),
);
let persistor = persistStore(store);
return {store, persistor};
};

我将redux-persist添加到此文件中,因为我希望主题在更改时保持不变。这个设置没有出现错误,但当我尝试更改主题时,它不会切换。我使用访问了主题的状态

const theme = useSelector(state => state.themeReducer.theme) 

这是themeReducer

import {lightTheme, darkTheme, SWITCH_THEME} from '../../components/index';
const initialState = {
theme: lightTheme,
};
const themeReducer = (state = initialState, action) => {
switch (action.type) {
case SWITCH_THEME:
return {
theme: action.theme,
};
default:
return state;
}
};
export default themeReducer;

这是switchTheme动作

import {SWITCH_THEME} from './../../redux';
export const switchTheme = theme => {
try {
return dispatch => {
dispatch({
type: SWITCH_THEME,
theme: theme,
});
};
} catch (error) {
console.log(error);
}
};

主题开关位于DrawerContent文件中,如下所示。CCD_ 5具有布尔值。

<Drawer.Section>
<Preferences>Preferences</Preferences>
<TouchableRipple onPress={() => {
theme.mode === 'light'
? dispatch(switchTheme(darkTheme))
: dispatch(switchTheme(lightTheme));
console.log('Theme state: ', theme.state);
console.log('Theme mode: ', theme.mode);
}}>
<View style={styles.preference}>
<Text style={{color: theme.text}}>Dark Theme</Text>
<View pointerEvents="none">
<Switch value={theme.state} />
</View>
</View>
</TouchableRipple>
</Drawer.Section>

我找到了我的解决方案。我从themeReducer中的错误位置导入SWITCH_THEME

相关内容

  • 没有找到相关文章

最新更新