React将类组件转换为功能组件不起作用

时间:2020-03-29 07:00:40

标签: javascript reactjs

我正在尝试将我的类Component转换为功能组件,但是它不起作用。

问题来自此行previousLocation = this.props.location;
我该如何替换功能组件中的那个

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>
        );
    }
}

我要做什么


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>
    );
}

1 个答案:

答案 0 :(得分:2)

How to get the previous props or state

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

用法:

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>
  );
}