简体   繁体   中英

React Convert class component to Functional component not working

I'm trying to convert my class Component to functional component but it doesn't work.

the problem comes from this line previousLocation = this.props.location;
how can i replace that in functional component

class App extends Component {
    previousLocation = this.props.location; //the problem comes from here
    render() {
        const { location } = this.props;
        const isModal = !!(
            location.state &&
            location.state.modal &&
            this.previousLocation !== location
        );
        return (
            <div>
                <Switch location={isModal ? this.previousLocation : location}>
                    <Route exact path="/" component={Gallery} />
                    <Route exact path="/img/:id" component={Gallery} />
                    <Route exact path="/img" component={ModalPage} />
                </Switch>
                {isModal ? <Route path="/img/:id" component={ModalPage} /> : null}
            </div>
        );
    }
}

what I'm trying to do


const App = (props) => {
    const {previousLocation} = props.location;
    const {location} = props;
    const isModal = !!(
        location.state &&
        location.state.modal &&
        previousLocation !== location
    );
    return (
        <div>
            <Switch location={isModal ? previousLocation : location}>
                <Route exact path="/" component={Gallery}/>
                <Route exact path="/img/:id" component={Gallery}/>
                <Route exact path="/img" component={ModalPage}/>
            </Switch>
            {isModal ? <Route path="/img/:id" component={ModalPage}/> : null}
        </div>
    );
}

How to get the previous props or state

const usePrevious = value => {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

Usage:

const App = ({ location }) => {
  // get previous location and cache current location
  const previousLocation = usePrevious(location);

  const isModal = !!(
    location.state &&
    location.state.modal &&
    previousLocation !== location
  );

  return (
    <div>
      <Switch location={isModal ? previousLocation : location}>
        <Route exact path="/" component={Gallery}/>
        <Route exact path="/img/:id" component={Gallery}/>
        <Route exact path="/img" component={ModalPage}/>
      </Switch>
      {isModal ? <Route path="/img/:id" component={ModalPage}/> : null}
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM