redux 获取状态中的更改值

ep6jt1vc  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(122)

我有一个项目,当状态通过WebSocket改变时,它会向服务器发送值,我使用的是redux-toolkit,我有一个这样的状态

const initialState = {
  exposure: false,
  whiteBalance: false,
  shutterSpeed: 1,
  iso: 50,
  temperature : 5500,
  tint : 0,
  brightness: { checked: false, value: 0 },
  hue: { checked: false, value: 0 },
  saturation: { checked: false, value: 0 },
  vibrance: { checked: false, value: 0 },
  contrast: { checked: false, value: 0 },
  gamma: { checked: false, value: 0 },
  sharpness: { checked: false, value: 0 },
};

const imageAdjustmentsSlice = createSlice({
  name: "imageAdjustments",
  initialState,
  reducers: {
    changeIso: (state, action: PayloadAction<number>): void => {
      state.iso = action.payload;
    },
    changeTemperature: (state,action: PayloadAction<number>): void => {
      state.temperature = action.payload;
    },
    changeTint: (state,action: PayloadAction<number>): void => {
      state.tint = action.payload;
    },
    // and other reducers
  }
});

const store = configureStore({  
  reducer: {
    imgAdjustments:imageAdjustmentsSlice.reducer,
  },
});

个字符
当videoStore发生变化时,我想将更改后的值发送到服务器。我想知道当状态发生变化时哪个值会发生变化。例如,我在某个地方使用调度更改了iso值。我只想获得更改后的iso值。像这样:

const changedValue = getChangedValue(state) // returns { iso : 200 }


是否有函数/钩子或其他方法来做到这一点?或者我应该重新配置redux?

yptwkmov

yptwkmov1#

对于这个行为/逻辑,没有“内置”React或React-Redux/Redux-Toolkit钩子,所以你需要自己实现它。我建议实现一个自定义的React钩子,它可以计算当前和以前的对象值之间的差异。
范例:

import { useEffect, useRef } from "react";

// Typical "usePrevious" value hook recipe
const usePrevious = (value) => {
  const ref = useRef();

  useEffect(() => {
    ref.current = value;
  });

  return ref.current;
};

const useObjectDiff = (current) => {
  const previous = usePrevious(current);

  const diff = {};

  if (current && previous) {
    Object.entries(current).forEach(([key, value]) => {
      if (previous[key] !== value) {
        diff[key] = value;
      }
    });
  }

  return Object.keys(diff).length ? diff : null;
};

字符串
演示:
x1c 0d1x的数据
使用方法:

const WSController = () => {
  const videoStore = useAppSelector((state) => state.imgAdjustments);
  const { sendMessage } = useWebSocket("ws://localhost:3000");

  const videoStoreDiff = useObjectDiff(videoStore);
    
  React.useEffect(() => {
    if (videoStoreDiff) {
      sendMessage(JSON.stringify(videoStore));
    }
  }, [videoStoreDiff]);

  return (
    ...
  );
}

相关问题