在一秒内将url从一个更改为另一个



React这里的初学者,通过编码学习,我有一个项目,我有个小问题(这个代码在某种程度上接近我的真实代码,无法共享真实代码(,

我的问题是,我怎么能在不到一秒钟的时间内拥有我的新快照:

设newSnapshot=api/cam/${site.identifier}/+${allCams[0].identifier}/snapshot

然后自动更改为:

设newSnapshot=api/cam/${site.identifier}/+${cam.identifier}/snapshot

英语不是我的母语,所以可能会出错,任何问题都可以问我。

const [state, setState] = useState({
snapshotUrl: "",
});
const updatePreview = () => {
const allCams=[{identifier: '7-7-7'}]
const site={identifier: '1-1-1'} 
const cam={identifier: '0-0-0'} 

let newSnapshot =
`api/cam/${site.identifier}/` +
`${cam.identifier}/snapshot`;
setState({
...state,
snapshotUrl: newSnapshot,
});
}

您需要一个包含setTimeoutuseEffect。此外,如果您计划使用[allCams, site, cam]deps数组运行此useEffect,请确保这些值以某种方式存储,使用useState或useMemo,因为您可以获得无限的useEffect执行和无限的render。

const { useState } = React;
function App() {
const [state, setState] = useState({
snapshotUrl: ""
});
const updatePreview = () => {
const allCams = [{ identifier: "7-7-7" }];
const site = { identifier: "1-1-1" };
const cam = { identifier: "0-0-0" };
const snStart = `api/cam/${site.identifier}/${allCams[0].identifier}/snapshot`;
const snAfter = `api/cam/${site.identifier}/${cam.identifier}/snapshot`;
setState((currState) => ({ ...currState, snapshotUrl: snStart }));
setTimeout(() => {
setState((currState) => ({ ...currState, snapshotUrl: snAfter }));
}, 1000);
};
return (
<div className="App">
<p>{state.snapshotUrl}</p>
<button type="button" onClick={updatePreview}>
Update
</button>
</div>
);
}
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App />
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
<div id="root"></div>

最新更新