在这里反应初学者,通过编码学习,我有一个我的项目,我有一个小问题(这个代码有点接近我的真实代码,不能分享真正的代码),
我的问题是,我如何才能在不到一秒钟的时间内拥有我的newSnapshot:
设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,
});
}
发布于 2022-09-12 13:13:40
您需要一个useEffect,其中包含setTimeout。另外,如果您计划使用useEffect deps数组运行此[allCams, site, cam] --确保以某种方式,使用useState或useMemo回传这些值,因为您可以获得无限的useEffect执行和无限重登。
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>
https://stackoverflow.com/questions/73689720
复制相似问题