【问题标题】:Wait for map response before return (React JS)在返回之前等待地图响应(React JS)
【发布时间】:2022-12-20 23:54:55
【问题描述】:
这是代码:
const [isAcces, setIsAcces] = useState(false);
useEffect(() => {
accesList
.filter((acces) => acces.idAcces === 2)
.map((acces, index) => setIsAcces(true));
}, []);
return <div>Hello World</div>;
如果“isAccess”为真,我想渲染“Hello World”。
如果没有,我使用<Navigate to="/" /> 进行重定向。
我知道“useEffect”在返回后呈现,但我找不到解决我的问题的解决方案(当然,“isAcces”在重定向之前始终为 false)。
我在谷歌上发现我可以使用“承诺”,但我不知道它是如何工作的。
有人可以帮我吗?
谢谢 !
【问题讨论】:
标签:
reactjs
dictionary
react-hooks
【解决方案1】:
如果我理解正确,你正在循环一个数组,如果那里有等于 2 的项目,你将 isAcces 设置为 true,对吗?
如果是,则过滤器后不需要 map()
您可以稍微简化您的代码。
function YourComponent({ accesList }) {
const [isAcces, setIsAcces] = useState(false);
useEffect(() => {
const newArr = accesList.filter((acces) => acces.idAcces === 2);
if (newArr.length > 0) {
setIsAcces(true);
}
}, []);
useEffect(() => {
if (isAcces) {
// import history from react-router-dom or any method to navigate to another route
history.push("/");
}
}, [isAcces]);
return <div>hello world!</div>
}