React native 使用Redux切换主题不起作用
这是我的configureStore.js文件React native 使用Redux切换主题不起作用,react-native,react-redux,redux-persist,React Native,React Redux,Redux Persist,这是我的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/a
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)
这是传感器的
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;
这是切换主题
动作
import {SWITCH_THEME} from './../../redux';
export const switchTheme = theme => {
try {
return dispatch => {
dispatch({
type: SWITCH_THEME,
theme: theme,
});
};
} catch (error) {
console.log(error);
}
};
主题开关位于DrawerContent
文件中,如下所示。主题.state
有一个布尔值
<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>
偏好
{
theme.mode===‘灯光’
?调度(切换主题(暗主题))
:调度(switchTheme(lightTheme));
log('Theme state:',Theme.state);
log('Theme模式:',Theme.mode);
}}>
黑暗主题
我找到了解决方案。我从themeReducer
的错误位置导入SWITCH\u主题