我正在构建一个 Ionic 7 和一个 REact 18 应用程序。我有一个带有提交按钮的组件,当用户单击“提交”按钮时,该组件会将路由推送到历史对象(旨在更改 URL)
const OrderItemRecipientComponent: React.FC = () => {
...
const history = useHistory();
const [isButtonDisabled, setButtonDisabled] = useState(false);
useEffect(() => {
// This effect will run after the component re-renders
if (isButtonDisabled) {
// move on to the payment
history.push("/payment");
}
}, [isButtonDisabled, history]);
const handleSaveAndContinue = () => {
setButtonDisabled(true); // Disable the button
// add the item to the cart
addToCart(orderItem);
};
return (
<>
...
<p>
<AddressForm
contactInfo={contactInfo}
setContactInfo={setContactInfo}
/>
</p>
<IonButton expand="full" onClick={handleSaveAndContinue} disabled={isButtonDisabled}>
Pay
</IonButton>
</>
);
};
export default OrderItemRecipientComponent;
然后我在我的 App.tsx 路由中定义了这个
<IonContent className="ion-padding" scroll-y>
<IonRouterOutlet>
...
<Route exact path="/payment">
<PaymentContainer />
</Route>
</IonRouterOutlet>
</IonContent>
</IonReactRouter>
问题是,通常当我单击“Pay”按钮时,尽管我看到 URL 中的路由发生了变化,但我并不总是看到呈现的 PaymentContainer 组件(原始组件仍然存在)。当我在浏览器上单击“刷新”时,我确实看到渲染了正确的组件。如何更正我的顺序,以便 PaymentContainer 组件在我的路线更改时呈现?
基于joshua-wyllie的答案here,其中提到了这个github问题:您需要在每个页面上都有一个包装
<IonPage>
(在您的情况下作为PaymentContainer
的根)。
如果这不能解决问题,您可以尝试以下解决方法: 正如yairopro在这篇文章中提到的那样,您可以尝试像这样强制更新:
const history = useHistory();
const [, forceUpdate] = useReducer(x => x + 1, 0);
useEffect(() => {
// This effect will run after the component re-renders
if (isButtonDisabled) {
// move on to the payment
history.push("/payment");
forceUpdate();
}
}, [isButtonDisabled, history]);