gpt4 book ai didi

javascript - 函数无法正确读取状态值

转载 作者:行者123 更新时间:2023-12-03 14:22:12 25 4
gpt4 key购买 nike

我的应用程序中有这个组件,我正在尝试实现无限滚动根据 this教程。

export const MainJobs = () => {
const [items, setItems] = useState([]);
const [ind, setInd] = useState(1);
const errText = useLang(
"sagas // Something went wrond // fasa"
);
const [element, setElement] = useState(null);
const incrementState = () => {
console.log(ind, ind + 1); //logs 1,2
setInd(ind + 1);
};
useEffect(() => {
const fetchInfo = async () => {
const res = await fetch(`/api/search/vacancy?page=${ind}`);
if (res.ok) {
const data = await res.json();
setItems(data);
} else {
pop({
icon: "error",
title: "Oops...",
text: errText
});
}
};
fetchInfo();
}, [ind]);
useEffect(() => {
const currentElement = element;
const currentObservor = observor.current;
if (currentElement) {
currentObservor.observe(currentElement);
}
return () => {
if (currentElement) {
currentObservor.unobserve(currentElement);
}
};
}, [element]);
const observor = useRef(
new IntersectionObserver(
entries => {
const first = entries[0];
if (first.isIntersecting) {
incrementState();
}
},
{ threshold: 1 }
)
);
return (
<div className="mainjobs-container">
...rest of markup
<div className="bottom" ref={setElement}></div>
</div>
);
};

它每次都会记录1,2,但不会增加ind。同样在 devtools 中 ing 递增到 2,然后停止。

每次调用 incrementState 函数时,我都需要递增 ind 。P.S 我认为问题出在 useRefObservor 中。

最佳答案

来自docs :

Why am I seeing stale props or state inside my function?

Any function inside a component, including event handlers and effects, “sees” the props and state from the render it was created in.

碰巧 incrementState 是在 useRef 内定义的,因此只能“看到”初始状态。

如果您只想修复单一状态,这非常简单:

const incrementState = () => {
setInd(prevInd => prevInd + 1);
}

我们使用 functional version of state setter ,这样我们就不会错过任何状态更新。

但是如果这个处理程序实际上依赖于另一个状态变量怎么办?

const observer = useRef();

// Adding a placeholder state for demo
const [secondState, setSecondState] = useState();

useEffect(() => {

const incrementState = () => {
// something to do with second state here
if(secondState)
setInd(prevInd => prevInd + 1);
};

observer.current = new IntersectionObserver(
entries => {
const first = entries[0];
if (first.isIntersecting) {
incrementState();
}
},
{ threshold: 1 }
);

}, [secondState]); // note dependency here, ensures that each updates "sees" the new version of function

useEffect(() => {
// observer and so on...
});

const { Component, useRef, useState, useEffect } = React;
const { render } = ReactDOM;

function App() {
const thingRef = useRef();
const [count, setCount] = useState(0);

const incrementCounter = () => {
setCount(prevCount => prevCount + 1);
};

const observer = useRef(
new IntersectionObserver(
entries => {
const first = entries[0];
if (first.isIntersecting) {
incrementCounter();
}
},
{ threshold: 1 }
)
);

useEffect(() => {
const currentElement = thingRef.current;
const currentObserver = observer.current;
if (currentElement) {
currentObserver.observe(currentElement);
}
return () => {
if (currentElement) {
currentObserver.unobserve(currentElement);
}
};
}, []);

return (
<main style={{ height: "600vh", position: "relative" }}>
<div
ref={thingRef}
style={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
height: '80vh',
border: '1px solid pink',
width: '98%',
textAlign: 'center',
}}
>
Thing
</div>
<p
style={{
backgroundColor: 'red',
borderRadius: '50%',
color: 'white',
width: '20px',
height: '20px',
lineHeight: '20px',
textAlign: 'center',
position: 'fixed',
top: '10px',
right: '80px',
margin: 0
}}
>{count}</p>
</main>
);
}

render(<App />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" />

关于javascript - 函数无法正确读取状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60978698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com