[英]My useState hook is not updating itself and when i am trying to get data using filter, its not working
When I am trying to get data from an array using filter and find, it's not getting filtered also the _ids are the same when I cross-checked the array, also useState is also not updating当我尝试使用过滤器和查找从数组中获取数据时,它没有被过滤,当我交叉检查数组时 _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
I am getting every data from context (c1)我从上下文(c1)中获取所有数据
sd is returning array of single object, so to get one first index I am returning sd[0] 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;
My guess from your code is that you should assign the filtered data when the component is rendered, not when first
changes:我对您的代码的猜测是,您应该在呈现组件时分配过滤后的数据,而不是在first
更改时分配:
useEffect(() => {
func(first_load_func());
}, []);
It may be useful to convert id
s toString()
before comparing them:在比较它们之前转换id
s toString()
可能很有用:
const sd = c1.data.filter((c1) => id.toString() === c1._id.toString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.