React Redux条件菜单屏幕渲染

pes8fvy9  于 2022-11-12  发布在  React
关注(0)|答案(1)|浏览(139)

我对react native很陌生。在我的应用程序中,我遇到了一个需要对菜单进行限制的情况。简单地说,我有一个redux列表,它保存了屏幕名称和真/假值。还有一些开关可以限制。但是我不能更新redux屏幕列表/值。请帮助我!

//screenReducer.js
  import {SET_CHANGE_MENU} from "./actions";

  const INITIAL_STATE={
      screen:[{name:'Screen1' ,value:true},{name:'Screen2',value:true},  {name:'Screen3',value:true},{name:'Screen4',value:true},{name:'Screen5',value:true}]

  export function screenReducer(state=INITIAL_STATE, action){
switch (action.type){
    case 'SET_CHANGE_MENU':
        return{...state,
            screen:state.screen.map(x=>x.name===action.name?{
            ...x,value:action.value}:x)}
    default:
        return state;
}}

    //actions.js
    export const SET_CHANGE_MENU='SET_CHANGE_MENU';
    export const changeMenu = (name,value) =>{
      return{type:SET_CHANGE_MENU, payload: name,value }
    }

     //rootReducer.js
  import {screenReducer} from "./screenReducer";
  export default combineReducers({
     screenState:screenReducer,
  })

    //store
   import {createStore,applyMiddleware} from "redux";
   import thunk from "redux-thunk";
   import rootReducer from "./rootReducer";
   const store=createStore(rootReducer,applyMiddleware(thunk));
   export default store;

    //App.js
   const App: () => Node = () => {
     useEffect(() => {
         SplashScreen.hide();
         requestUserPermission().then(r=>{});
         NotificationListener();
       },
       [])
       return (
       <Provider store={store}>
       <MainNavigator />
       </Provider>
     );
   };

    //Settings.js (screen enable switch in this screen)
   import {useDispatch, useSelector} from "react-redux";
   import {changeMenu} from "../store/redux/actions";
   import AsyncStorage from "@react-native-async-storage/async-storage";

   const dispatch=useDispatch();
   const {screen}=useSelector(state=>state.screenState);

   <View style={{flexDirection:'row', margin:5}}>
      <Text>Screen 1</Text>
      <Switch
       trackColor={{ false: "#767577", true: "#31b031" }}
       thumbColor={screen[0]?.value? "#fff" : "#f4f3f4"}
       ios_backgroundColor="#3e3e3e"
       onValueChange={()=>dispatch(changeMenu({name:'Screen1',value:false}))}
       value={screen[0]?.value}
       style={{marginLeft:165}}
       />
   </View>
2j4z5cfb

2j4z5cfb1#

在减速器中,您正在访问action.name而不是action.payload

export function screenReducer(state=INITIAL_STATE, action){
  switch (action.type){
    case [SET_CHANGE_MENU]:
        return {
          ...state,
          screen: state.screen.map(x => x.name === action.payload? {
              ...x,
              value: action.payload
            } : x
          )
        };
    default:
      return state;
  }
}

您也没有使用正确的参数调用操作创建者

onValueChange{(value) => dispatch(changeMenu('Screen1', value))}

相关问题