0

在父组件中为嵌套路由设置动画时遇到了这个问题,父组件将被卸载并再次安装,并且动画重新启动我需要阻止父组件的重新渲染这里是我在 codesanbox 中的代码。祝大家编码愉快 新链接代码沙盒

import React from "react";
import "./styles.css";
import { Route, Switch, Link, useLocation } from "react-router-dom";
import { AnimatePresence } from "framer-motion";
import Home from "./component/home";
import OtherComponent from "./component/othercomoponent";
import ComponentWithNestedRoute from "./component/componentwithnestedroute";
export default function App() {
  const location = useLocation();
  return (
    <div className="App">
      <div className="nav-container">
        <p>
          <Link to="/home">home</Link>
        </p>
        <p>
          <Link to="/ComponentWithNestedRoute">
            Component With nested route
          </Link>
        </p>
        <p>
          <Link to="/otherComponent">Other Component</Link>
        </p>
      </div>
      <AnimatePresence exitBeforeEnter initial={false}>
        <Switch location={location} key={location.pathname}>
          <Route path={`/home`}>
            <Home />
          </Route>
          <Route path={"/otherComponent"}>
            <OtherComponent />
          </Route>
          <Route path={"/ComponentWithNestedRoute"}>
            <ComponentWithNestedRoute />
          </Route>
        </Switch>
      </AnimatePresence>
    </div>
  );
}

嵌套组件是这样的,每次当我单击一个路由时,组件将卸载并再次安装,并且嵌套组件的动画重复我希望我的嵌套永远不会再重新渲染,当我的路由像 /ComponentWithNestedRoute/:nested 它只是重新渲染并重新启动动画的子组件

import React from "react";
import { Link, withRouter, Route, Switch } from "react-router-dom";
import { motion, AnimatePresence } from "framer-motion";
import Nested1 from "./Nested1";
import Nested2 from "./Nested2";
const containerVariants = {
  hidden: {
    opacity: 0
  },
  visible: {
    opacity: 1,
    transition: {
      duration: 0.25,
      when: "beforeChildren"
    }
  },
  exit: {
    opacity: 0,
    transition: {
      ease: "easeInOut",
      duration: 1
    }
  }
};
class ComponentWithNestedRoute extends React.Component {
  render() {
    console.log(this.props.location);
    return (
      <motion.div
        variants={containerVariants}
        initial="hidden"
        animate="visible"
        exit="exit"
        className="nestedComponent"
      >
        <p>
          <Link to={`${this.props.match.path}/nested1`}>Nested1</Link>
        </p>
        <p>
          <Link to={`${this.props.match.path}/nested2`}>Nested2</Link>
        </p>

        <div className="route-nested-wrapper">
          
            <Switch>
              <Route path={`${this.props.match.path}/nested1`}>
                <Nested1 />
              </Route>
              <Route path={`${this.props.match.path}/nested2`}>
                <Nested2 />
              </Route>
            </Switch>
     
        </div>
      </motion.div>
    );
  }
}

export default withRouter(ComponentWithNestedRoute);

希望这很清楚。再次快乐编码

4

0 回答 0