如何使用react和typescript基于url更新useeffect中的状态



当用户在页面中时,我想将right属性从16px更改为40px"items/:itemId";使用react和typescript。

下面是我的组件片段,

const root = () => {
<PopupContextProvider>
<App/>
</PopupContextProvider>
}

export const PopupContextProvider = ({ children }: any) => {
return (
<popupContext.Provider value={context}>
{children}
{(condition1 || condition2) && (
<Popup onHide={dismiss} />
)}
</popupContext.Provider>
);
}
export function Popup({ onHide }: Props) {
const location = useLocation();
const [isView, setIsView] = React.useState(false);
if (location.pathname === '/items/:itemId') {
setIsView(true);//here doesnt change to true. how can i do the same 
//in useeffect or something that updates 
}
return (
<Dialog isView={isView}>
<DialogBody>
<span>Title</span>
<Description/>
</DialogBody>
<Actions>
<span>Hide</span>
</Actions>
</Dialog>
);
}

const Dialog = styled.div<isView?:boolean>`
position: fixed;
${({ isView }) => isView && 'right:  40px;'}
display: flex;
flex-direction: column;
`;

在上面的代码段中,我检查位置并将isView状态更新为true。

现在即使当用户在页面"中时/items/:itemId";isView不会从false更新为true。

如何在useeffect中更新状态???

有人能帮我吗?谢谢

您根本不需要isView状态,只需将其设为const即可。

export function Popup({ onHide }: Props) {
const location = useLocation();
const isView = location.pathname === '/items/:itemId';
return (
<Dialog isView={isView}>
<DialogBody>
<span>Title</span>
<Description/>
</DialogBody>
<Actions>
<span>Hide</span>
</Actions>
</Dialog>
);
}

只有当您需要记住一些确实发生了变化的事情时,才需要State,比如用户在React重新发送组件时输入信息或单击按钮。但是,在这种情况下,如果不重新加载页面并获得组件的新实例,您可能不会更改路径。

如果你真的想使用useEffect,你可以放一个空数组作为第二个arg,这意味着它只会在创建组件时运行,就像类React中的componentDidMount一样。

export function Popup({ onHide }: Props) {
const location = useLocation();
const [isView, setIsView] = React.useState(false);
useEffect(() => {
if (location.pathname === '/items/:itemId') {
setIsView(true);//here doesnt change to true. how can i do the same 
//in useeffect or something that updates 
}
}, []);
return (
<Dialog isView={isView}>
<DialogBody>
<span>Title</span>
<Description/>
</DialogBody>
<Actions>
<span>Hide</span>
</Actions>
</Dialog>
);
}

您可能会收到一条警告,需要在末尾将isView添加到空数组中。React希望您观察正在修改的值,并在它们更改时调用useEffect。你可以添加它,但它很奇怪,因为它永远不会改变。

你可以将isView存储在ref中,这样你就不会得到警告,因为ref更新不会导致重新发布,但同样没有理由为重新发布存储这个变量——它可以快速轻松地计算。

最新更新