我的useState钩子没有更新自己,当我试图使用过滤器获取数据时,它不工作



当我试图使用过滤器从数组中获取数据时,它没有被过滤当我交叉检查数组时,_id是相同的,useState也没有更新

1. How should I filter one element from an array, Am I doing this right?
2. useState is not working, not updating data

我从上下文(c1)获取每个数据

sd返回单个对象的数组,因此为了获得一个第一个索引,我返回sd[0]

const ReadTemplate = (props) => {
const c1 = useContext(PostsContext);
const [first, myData] = useState({});
const first_load_func = () => {
const id = props.match.params.id;
const sd = c1.data.filter((c1) => id === c1._id);
const business_props = c1.business_data.filter((c1) => id === c1._id);
const startups_props = c1.startups_data.filter((c1) => id === c1._id);
const tech_props = c1.tech_data.filter((c1) => id === c1._id);
const sports_props = c1.sports_data.filter((c1) => id === c1._id);
if (sd) {
return sd[0];
} else if (business_props) {
return business_props[0];
} else if (startups_props) {
return startups_props[0];
} else if (tech_props) {
return tech_props[0];
} else if (sports_props) {
return sports_props[0];
} else {
return <MyAlert />;
}
};
const func = (data) => {
if (data) {
setTimeout(() => {
myData(data);
}, 1000);
console.log('ye first hai');
console.log(first._id);
console.log('ye data hai');
console.log(data);
} else {
console.log('No');
}
};
useEffect(() => {
first_load_func();
func(first_load_func());
}, [first]);
return (
<>
<PostDesign props={first} />
</>
);
};
export default ReadTemplate;

我从您的代码中猜测,您应该在组件呈现时分配过滤数据,而不是在first更改时:

useEffect(() => {
func(first_load_func());
}, []);

在比较idtoString()之前,将它们进行转换可能是有用的:

const sd = c1.data.filter((c1) => id.toString() === c1._id.toString());

最新更新