[英]How to call a function in React when two components are not mounted?
當單個 React 組件即將卸載時調用(redux)function 可以通過在componentWillUnmount
中調用 function 來完成。 但是我想知道當沒有安裝兩個 React 組件(位於單獨的 URL 后面)時,如何調用(redux)function。 這是一個例子:
class App extends React.Component {
render() {
return (
<Router history={history}>
<Switch>
<Route component={Foo} ... />
<Route component={Bar} ... />
// Many other routes
</Switch>
</Router>
);
}
}
class Foo extends React.Component<Props, State> {
componentWillUnmount() {
if (!navigated_to_bar()) {
alert("Clear state");
}
}
}
class Bar extends React.Component<Props, State> {
componentWillUnmount() {
if (!navigated_to_foo()) {
alert("Clear state");
}
}
}
我只想在用戶離開 Foo 和 Bar 組件時才調用alert
; 他們可以根據需要多次在這些組件之間導航,而不會觸發alert
呼叫。
我在尋找的解決方案方面相當靈活:我希望我需要架構范式轉變。 我在想解決方案可能是讓 Foo/Bar 有一個共同的父組件並以某種方式調整路由器。
最簡單的解決方案是使用父->子層次結構並從那里更新。 這是典型的反應約定; 傳入允許您更新父級 state 的 function。
class App extends React.Component {
componentDidMount() {
this.state = {
routedToFoo: null,
routedToBar: null
}
}
componentDidUpdate(_, prevState) {
if (prevState.routedToFoo !== this.state.routedToFoo &&
prevState.routedToBar !== this.state.routedToBar) {
if (this.state.routedToFoo === false && this.state.routedToBar === false)
alert("Clear state");
}
}
/* -- snip -- */
<Route component={<Foo setRouted={routedToFoo => this.setState({ routedToFoo })} ... />
<Route component={<Bar setRouted={routedToBar => this.setState({ routedToBar })}/>} ... />
/* -- snip -- */
}
然后在 Bar 和 Foo 內部:
componentDidMount() {
this.props.setRouted(true);
}
componentWillUnmount() {
this.props.setRouted(false);
}
在這里,我正在處理 componentDidUpdate 中的副作用。 我們聽聽這兩個值是否為假,並且至少有一個值已從以前的 state 更新,然后我們稱之為“清除狀態”警報。
但是,如果這不夠靈活,那么您可能需要考慮使用 redux。 https://redux.js.org/introduction/getting-started
或Context
: https://reactjs.org/docs/context.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.