[英]React Convert class component to Functional component not working
我正在尝试将我的类 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>
);
}
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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.