我使用 React-Redux 制作了一个反应网络摄像头应用程序进行状态管理
用于拍照并将 base64 发送到各自状态的网络摄像头代码
const videoConstraints = {
width: 250,
height: 400,
facingMode: "user",
};
const WebcamCapture = () => {
const webcamRef = useRef(null);
const dispatch = useDispatch();
const history = useHistory();
// It will prevent unnecessary re-renders.
const capture = useCallback(() => {
const imageSrc = webcamRef.current.getScreenshot();
console.log("imageSrc")
dispatch(setCameraImage(imageSrc))
history.push("/preview")
}, [webcamRef])
return (
<div className="webcamCapture">
<Webcam
audio={false}
height={videoConstraints.height}
width={videoConstraints.width}
screenshotFormat="image/jpeg"
ref={webcamRef}
videoConstraints={videoConstraints}
/>
<button className="webcamCapture__button"
onClick={capture}
>
<RadioButtonUncheckedIcon className="webcamCapture__button"
/>
</button>
</div>
)
Redux 代码用于状态管理
export const cameraSlice = createSlice({
name: 'camera',
initialState: {
cameraImage: null,
},
reducers: {
setCameraImage: (state, action) => {
state.cameraSlice = action.payload;
},
resetCameraImage: (state) => {
state.cameraImage = null;
},
},
});
export const { setCameraImage, resetCameraImage } = cameraSlice.actions;
export const selectCameraImage = (state) => state.camera.cameraImage;
export default cameraSlice.reducer;
预览捕获的图像
function Preview() {
const cameraImage = useSelector(selectCameraImage);
const history = useHistory();
const dispatch = useDispatch();
console.log(cameraImage);
useEffect(() => {
if(!cameraImage) {
history.replace("/")
}
}, [cameraImage, history])
const closePreview = () => {
dispatch(resetCameraImage());
history.replace("/");
}
return (
<div className="preview">
<button
className="preview__close"
onclick={closePreview}
>
<CloseIcon
className="preview__close"
/>
</button>
<img src={atob(cameraImage)} alt="mage" />
</div>
)
}
问题是在将图像 base64 url 存储到 setCameraImage 之后,我无法在预览屏幕和控制台中预览存储的图像(说 - “null”),它总是将我重定向到“/”页面,即使在 url 之后正确存储在redux中。我可以在控制台中查看它,所以请帮我解决这个问题
提前致谢
请注意,马吉..