使用效率不填充所有状态
因此,这是我的代码,我正在尝试通过用户过滤我的报价,我打电话给我所有的报价,所有用户和所有状态都已饱满,但是当我试图过滤用户的用户过滤报价时,状态保持空置,但是当我在我的键盘上击中空格键,状态变得完整,就像空格键正在触发使用效果以填充状态,
const [offer, setOffer] = useState([]);
const [user, setUser] = useState({});
const[useroffers,setUseroffer]=useState([]);
const isOffer = async () => {
const oflg = await GetAllOff();
setOffer(oflg);
};
const isLoggedIn = async () => {
const userLg = await CurrentUser();
setUser(userLg.data.user);
};
const isUseroffer = async()=>{
setUseroffer(offer.filter((el)=>el.createdbyId === user._id));
};
useEffect( () => {
isOffer();
isLoggedIn();
isUseroffer();
}, []);
console.log(offer);
console.log(user)
console.log(useroffers);
因此使用效果正在填充报价和用户状态,但没有填充用户offers state state intil i mign
SO this is my code, i'm trying to filter my offers by there users , i have called all my offers and all my user and there states are full but when i try to filter offers by there users the state stay empty but when i hit spacebar on my keyboard the state get full like it's the spacebar is triggering useEffect to fill the state
const [offer, setOffer] = useState([]);
const [user, setUser] = useState({});
const[useroffers,setUseroffer]=useState([]);
const isOffer = async () => {
const oflg = await GetAllOff();
setOffer(oflg);
};
const isLoggedIn = async () => {
const userLg = await CurrentUser();
setUser(userLg.data.user);
};
const isUseroffer = async()=>{
setUseroffer(offer.filter((el)=>el.createdbyId === user._id));
};
useEffect( () => {
isOffer();
isLoggedIn();
isUseroffer();
}, []);
console.log(offer);
console.log(user)
console.log(useroffers);
So useEffect is filling the offers and user States but not filling the useroffers state intil i click on the spacebar
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
用户offers
都取决于用户
和goder> goder
,但是您试图以与这两个相同的渲染周期进行设置。更新的状态值直到设置渲染循环后才可用,因此setUserOffers
无法访问正确更新所需的值。为了解决此问题,您可以声明第二个useffect
,该取决于user
和gode> gode> goder
,以便随着这些值的更新,因此您过滤后的数组也是如此。codesandbox
您可以做到通过等待
要约
和user
值,并在单个中都在使用
中,然后直接使用它们来设置所有三个状态。 (这将仅导致单个rerender,而不是上一个示例中可能的四个)codesandbox
useroffers
is dependent on bothuser
andoffer
but you are trying to set it in the same render cycle as those two. Updated state values aren't available until the render cycle after they are set, sosetUseroffers
doesn't have access to the values it needs to update properly. To solve this you can declare a seconduseEffect
which is dependent onuser
andoffer
so that as those values update so does your filtered array.codesandbox
Alternatively you can do it all in a single
useEffect
by awaiting theoffer
anduser
values and using them directly to set all three states once they are available. (This will result in only a single rerender rather than the possible four in the previous example)codesandbox