我正在阅读有关Algolia和Next的文档,并试图使URL显示在地址栏中,大多数示例都作为类组件使用,但是我正在使用的应用程序使用了Hooks。我正在尝试在我的网站上测试一些示例,但是当我不断收到错误消息时,我一直停留在如何正确将React中的类应用转换为钩子上。
类示例:
const updateAfter = 400;
const createURL = (state) => `?${qs.stringify(state)}`;
const searchStateToUrl = (props, searchState) =>
searchState ? `${props.location.pathname}${createURL(searchState)}` : '';
const urlToSearchState = ({ search }) => qs.parse(search.slice(1));
class App extends Component {
state = {
searchState: urlToSearchState(this.props.location),
lastLocation: this.props.location,
};
static getDerivedStateFromProps(props, state) {
if (props.location !== state.lastLocation) {
return {
searchState: urlToSearchState(props.location),
lastLocation: props.location,
};
}
return null;
}
onSearchStateChange = searchState => {
clearTimeout(this.debouncedSetState);
this.debouncedSetState = setTimeout(() => {
const href = searchStateToURL(searchState);
this.props.router.push(href, href, {
shallow: true
});
}, updateAfter);
this.setState({ searchState });
};
我的转换尝试:
const createURL = state => `?${qs.stringify(state)}`;
const pathToSearchState = path =>
path.includes("?") ? qs.parse(path.substring(path.indexOf("?") + 1)) : {};
const searchStateToURL = searchState =>
searchState ? `${window.location.pathname}?${qs.stringify(searchState)}` : "";
const DEFAULT_PROPS = {
searchClient,
indexName: "instant_search"
};
const Page = () => {
const [searchState, setSearchState] = useState(<not sure what goes here>)
const [lastRouter, setRouterState] = useState(router)
Page.getInitialProps = async({ asPath }) => {
const searchState = pathToSearchState(asPath);
const resultsState = await findResultsState(App, {
...DEFAULT_PROPS,
searchState
});
return {
resultsState,
searchState
};
}
//unsure how to convert here
static getDerivedStateFromProps(props, state) {
if (!isEqual(state.lastRouter, props.router)) {
return {
searchState: pathToSearchState(props.router.asPath),
lastRouter: props.router
};
}
return null;
}
const onSearchStateChange = searchState => {
clearTimeout(debouncedSetState);
const debouncedSetState = setTimeout(() => {
const href = searchStateToURL(searchState);
router.push(href, href, {
shallow: true
});
}, updateAfter);
setSearchState({ searchState });
};