我正在使用搜索功能。我想在路由中触发一个回调函数,以在数据进入搜索组件之前获取所有数据。
喜欢这个:
<Route path="/search/:query" component={QuestionSearchContainer} onChange={()=>fetchData(query?) }/>
但是我如何在搜索URL中获取查询关键字以将其作为参数放入我的fetchData中?
如果您不想使用QuestionSearchContainer组件进行数据获取,则可以制作一个高阶组件来包装它,以便为您进行数据获取。
您可以轻松地修改此HOC,以仅在数据加载完成时也返回Wrapped组件。
const withFetchData=(Component)=>({children,...props})=>{
const {query} = useParams();
useEffect(()=>{
fetchData(query);
},[query])
return <Component {...props}/>
}
const QuestionSearchContainerWithFetchData = withFetchData(QuestionSearchContainer);
const Parent = ()=>{
return <Route path="/search/:query" component={QuestionSearchContainerWithFetchData}/>
}
另一种选择是创建一条符合您期望的特殊路线。例如,每次参数更改时,此OnChangeRoute函数将使用当前参数调用回调onChangeParams
。
function InnerOnChangeRoute({ onParamsChange, Component, ...rest }) {
const onChangeRef = useRef(onParamsChange);
useEffect(()=>{
onChangeRef.current=onParamsChange;
},[onParamsChange])
useEffect(() => {
onChangeRef.current(rest.match.params);
}, [rest.match.params]);
return <Component {...rest} />;
}
// A wrapper for <Route> that redirects to the login
// screen if you're not yet authenticated.
function OnChangeRoute({ Component, onParamsChange, ...rest }) {
return (
<Route
{...rest}
render={(data) => (
<InnerOnChangeRoute
Component={Component}
onParamsChange={onParamsChange}
{...data}
/>
)}
/>
);
}