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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React将类组件转换为功能组件不起作用相关的知识,希望对你有一定的参考价值。

我正在尝试将我的类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>
    );
}
答案

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

以上是关于React将类组件转换为功能组件不起作用的主要内容,如果未能解决你的问题,请参考以下文章

如何将类组件转换为功能组件?

将类组件转换为功能组件 TypeError: users.filter is not a function

将类组件转换为功能组件

将类重构为 React 中的功能组件

在 React 中将类组件转换为功能组件

使用钩子将类组件转换为函数式