无法理解为什么reducer“showCurImg”中的过滤方法不能正常工作。我正在尝试过滤我的状态“gallery”,它是对象数组,其中对象包含文件(用户上传的图像)和id,它应该返回我的对象与id,但返回空数组。
例如,如果我用'!=='改变了我的过滤函数,它会返回一个里面有“代理对象”的数组。我的代码有什么问题吗?
这是我的
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RootState } from "../../app/store";
export interface imgItem {
imgItem: File;
id: number;
}
export interface imgs {
preview: imgItem[];
gallery: imgItem[];
curImg: {};
}
const initialState: imgs = {
preview: [],
gallery: [],
curImg: {},
};
export const imgsSlice = createSlice({
name: "userImgs",
initialState,
reducers: {
previewImgs: (state, action: PayloadAction<imgItem[]>) => {
state.preview = action.payload;
},
cleanPreview: (state) => {
state.preview = [];
},
addToGallery: (state, action: PayloadAction<imgItem[]>) => {
state.gallery = [...state.gallery, ...action.payload];
},
showCurImg: (state, action: PayloadAction<Number>) => {
const gal = state.gallery;
const filteredArray = gal.filter((item) => item.id === action.payload);
console.log(filteredArray);
},
},
});
export const { previewImgs, addToGallery, cleanPreview, showCurImg } =
imgsSlice.actions;
export const imgsArr = (state: RootState) => state.getImgs.preview;
export default imgsSlice.reducer;
从用户接收文件的组件
import React, { ChangeEvent } from "react";
import { useAppDispatch, useAppSelector } from "../app/hooks";
import Preview from "./Preview";
import {
addToGallery,
cleanPreview,
previewImgs,
} from "../features/imgs/imgsSlice";
import styles from "./FormImgs.module.css";
export default function FormImgs() {
const { preview } = useAppSelector((state) => state.getImgs);
const changeHandler = (e: ChangeEvent<HTMLInputElement>) => {
const chosenFiles = Array.prototype.slice.call(e.target.files);
const res = [];
for (const item of chosenFiles) {
const imgId = Math.random();
res.push({ imgItem: item, id: imgId });
}
console.log(res);
dispatch(previewImgs(res));
};
const submitHandler = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
dispatch(addToGallery(preview));
dispatch(cleanPreview());
console.log(preview);
};
const dispatch = useAppDispatch();
return (
<div className={styles.form}>
<p>Add an amazing photo from your device to your gallery</p>
<form action="#" onSubmit={submitHandler}>
<div className={styles.selectBtn}>
<input
type="file"
accept="image/*"
multiple
onChange={changeHandler}
title="Select images"
id="select"
style={{ display: "none" }}
/>
<label htmlFor="select">Select file</label>
</div>
{preview.length ? (
<>
<Preview />
<button type="submit">Add to gallery</button>
</>
) : (
""
)}
</form>
</div>
);
}
1条答案
按热度按时间g2ieeal71#
通过Math.random()创建id时出现问题。我应该使用“parseFloat”而不是“parseInt”