‘useNavigate’ 未从 ‘react-router-dom’ 导出
2021-04-26
9672
我正在尝试在我的 js 页面中使用
useNavigate
。下面是我尝试使用它的方法:
import { loadStripe } from '@stripe/stripe-js';
import firebase from 'firebase';
import "firebase/auth";
import * as routes from '../routes';
import './checkout.css';
import React, { useState, useEffect } from "react";
import MyGifSpinner from './manageSubSpinner';
import './manageSubSpinner.css';
import ReactDOM from 'react-dom';
import myGif from '../pages/spinner';
import myGifSpinner from './manageSubSpinner';
import { doSignOut } from '../models/AuthorizationHome';
import {useNavigate} from 'react-router-dom';
const firestore = firebase.firestore();
const app = firebase.app();
export async function createCheckoutSession(activtyStatus){
const navigate = useNavigate();
let user = firebase.auth().currentUser;
if (user == null) {
navigate('/clients')
}
console.log(user)
if (activtyStatus == "canceled") {
console.log("sub is cancelled")
//live price
price = 'price_1IfmDsKDPaWWeL1ywjMTGarh'
}
console.log("activity status is: " + activtyStatus)
const checkoutSessionRef = await firestore
.collection('customers')
.doc(user.uid)
.collection('checkout_sessions')
.add({
price: price,
success_url: "http://localhost:3000/clients",
cancel_url: "http://localhost:3000/signin",
});
// Wait for the CheckoutSession to get attached by the extension
checkoutSessionRef.onSnapshot(function (snap) {
const { error, sessionId } = snap.data();
if (error) {
console.log(`An error occured: ${error.message}`);
return;
}
if (sessionId) {
const stripe = window.Stripe('pk');
console.log("going to stripe: ")
console.log("line 116 checkout.js")
stripe.redirectToCheckout({sessionId: sessionId})
console.log("logged stripe")
}
});
}
但我仍然收到该错误。我使用的是 react-router-dom 版本 5.2.0 和 react 版本 17.0.2。请帮忙 :(
1个回答
useNavigate
是 v6 中的新钩子,它取代了
useHistory
钩子。
由于您仍在使用 v5,因此您应该导入并使用
useHistory
钩子来发出命令式导航。
import { useHistory } from 'react-router-dom';
...
const history = useHistory();
const user = firebase.auth().currentUser;
useEffect(() => {
if (!user) {
history.push('/clients');
}
}, [user]);
Drew Reese
2021-04-26