进入路由时触发函数(react-router-dom)
Triggering a function when entering a route (react-router-dom)
const Main = () => (
<div>
<Header />
<StyledMain>
<Header />
<Switch>
<Route exact path="/" component={Splash} render={()=>{alert('dd"')}}/>
<Route path="/files" component={Files} />
<Route path="/archived" component={Archived} />
<Route path="/extract/:filename" component={Extract} />
<Route path="/docs/api" component={Docs} />
</Switch>
</StyledMain>
</div>
)
在我的 main.js 中,我试图在进入主要路线 ('/')
时触发警报。但是,这不起作用。
我也试过 onEnter
,但意识到这是旧版本。
这是正确的用法吗?
您可以按照@Tholle 在评论中的建议在您的 Splash 组件中放置警报。但是使用 render
你可以在不使用组件的情况下做到这一点:
const Main = () => (
<div>
<Header />
<StyledMain>
<Header />
<Switch>
<Route exact path="/" render={() => {
alert('dd"');
return <Splash />;
}
}/>
<Route path="/files" component={Files} />
<Route path="/archived" component={Archived} />
<Route path="/extract/:filename" component={Extract} />
<Route path="/docs/api" component={Docs} />
</Switch>
</StyledMain>
</div>
)
const Main = () => (
<div>
<Header />
<StyledMain>
<Header />
<Switch>
<Route exact path="/" component={Splash} render={()=>{alert('dd"')}}/>
<Route path="/files" component={Files} />
<Route path="/archived" component={Archived} />
<Route path="/extract/:filename" component={Extract} />
<Route path="/docs/api" component={Docs} />
</Switch>
</StyledMain>
</div>
)
在我的 main.js 中,我试图在进入主要路线 ('/')
时触发警报。但是,这不起作用。
我也试过 onEnter
,但意识到这是旧版本。
这是正确的用法吗?
您可以按照@Tholle 在评论中的建议在您的 Splash 组件中放置警报。但是使用 render
你可以在不使用组件的情况下做到这一点:
const Main = () => (
<div>
<Header />
<StyledMain>
<Header />
<Switch>
<Route exact path="/" render={() => {
alert('dd"');
return <Splash />;
}
}/>
<Route path="/files" component={Files} />
<Route path="/archived" component={Archived} />
<Route path="/extract/:filename" component={Extract} />
<Route path="/docs/api" component={Docs} />
</Switch>
</StyledMain>
</div>
)