gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:58:18 24 4
gpt4 key购买 nike

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

问题来自这一行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>
);
}

关于javascript - React 将类组件转换为功能组件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60911112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com