此路由器动画可以处理页面加载,但是当我使用导航栏进行导航时,它会更改网址,但是页面不会更改,或者更改时间很长。
import React, { useContext } from "react";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, __RouterContext } from "react-router-dom";
import { useTransition, animated } from "react-spring";
import "assets/scss/material-kit-react.scss?v=1.4.0";
// pages for this product
import LandingPage from "views/LandingPage/LandingPage.jsx";
import ProfilePage from "views/ProfilePage/ProfilePage.jsx";
var hist = createBrowserHistory();
const App = () => {
const { location } = useContext(__RouterContext);
const transitions = useTransition(location, location => location.pathname, {
from: { opacity: 0, transform: "translate(100%,0)" },
enter: { opacity: 1, transform: "translate(0%,0)" },
leave: { opacity: 0, transform: "translate(-50%,0)" }
});
return (
<>
{transitions.map(({ item, props, key }) => (
<animated.div key={key} style={props}>
<Router history={hist}>
<Switch location={item}>
<Route path="/profile-page" component={ProfilePage} />
<Route path="/" component={LandingPage} />
</Switch>
</Router>
</animated.div>
))}
</>
);
};
export default App;
这是我的NavLink的结构
<Link
exact
to="/profile-page"
className={classes.link}
activeClassName="active"
>
答案 0 :(得分:0)
我试图重现您的问题。我认为您的问题可能是,您还在App的内部和外部使用了Router。因为useContext没有外部路由器将无法工作。 因此,解决方案是从应用的渲染中删除路由器。这是我完整的工作示例:
import React, { useContext } from 'react';
import { createBrowserHistory } from 'history';
import {
Route,
Switch,
Link,
__RouterContext,
BrowserRouter
} from 'react-router-dom';
import { useTransition, animated } from 'react-spring';
import ReactDOM from 'react-dom';
function App() {
return (
<BrowserRouter>
<Home />
</BrowserRouter>
);
}
// pages for this product
const LandingPage = () => {
return (
<div>
<h1>LandingPage</h1>
<Link to="/profile-page">profile</Link>
</div>
);
};
const ProfilePage = () => {
return (
<div>
<h1>Profile</h1>
<Link to="/">main</Link>
</div>
);
};
const Home = () => {
const { location } = useContext(__RouterContext);
const transitions = useTransition(location, location => location.pathname, {
from: {
position: 'absolute',
width: '100%',
opacity: 0,
transform: 'translate(100%,0)'
},
enter: { opacity: 1, transform: 'translate(0%,0)' },
leave: { opacity: 0, transform: 'translate(-50%,0)' }
});
return (
<>
{transitions.map(({ item, props, key }) => (
<animated.div key={key} style={props}>
<Switch location={item}>
<Route path="/profile-page" component={ProfilePage} />
<Route path="/" component={LandingPage} />
</Switch>
</animated.div>
))}
</>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
export default App;