【发布时间】:2021-07-02 01:57:34
【问题描述】:
我不知道我做错了什么,但我无法从我从 API 收到的对象中访问 option.slug。我正在尝试更改通过 URL slug 并更改我的应用程序的路由。我正在尝试使用我的useAutocomplete() 定义中的onChange 属性来做到这一点。
访问option.slug 或任何其他属性在我的 JSX 结构中运行良好。如您所见,我正在抓取 option.title 等以呈现效果良好的列表项...
我没有抓住实际的 slug,而是继续获取“/components/undefined”的路线
但是,当我尝试访问 useAutocomplete() 定义中组件顶层的 option.slug 时,它似乎不起作用。不过,根据原始文档,这就是这样做的方法。
https://material-ui.com/components/autocomplete/#useautocomplete
export default function NavigationSearch({ onClose, results }) {
const router = useRouter();
const {
getRootProps,
getInputLabelProps,
getInputProps,
getListboxProps,
getOptionProps,
groupedOptions
} = useAutocomplete({
id: 'use-autocomplete-demo',
options: results,
getOptionLabel: (option) => option.title,
onChange: (option) => router.push(`/components/${option.slug}`)
});
return (
<React.Fragment>
{/* 1. SEARCH INPUT */}
<Container maxWidth="md" disableGutters>
<Box display="flex" width="100%">
<motion.div
style={{ width: 'inherit' }}
initial="hidden"
animate="visible"
variants={animation}>
<Box display="flex" width="inherit">
<Search width="inherit" {...getRootProps()}>
<SearchIcon color="primary" />
<InputBase
placeholder="Search for components, patterns..."
style={{ color: 'inherit', width: 'inherit' }}
autoFocus
{...getInputProps()}
/>
</Search>
</Box>
</motion.div>
<IconButton color="primary" onClick={onClose}>
<CloseIcon />
</IconButton>
</Box>
</Container>
{/* SEARCH RESULTS */}
<BackdropOverlay open={true} onClick={onClose}>
<Container maxWidth="md" disableGutters>
{groupedOptions.length > 0 ? (
<Results>
<List
{...getListboxProps()}
subheader={
<Box paddingX={2}>
<Typography
variant="overline"
color="textSecondary"
gutterBottom>
Popular search results
</Typography>
</Box>
}>
{groupedOptions.map((option, index) => (
<Item
button
key={option.title}
{...getOptionProps({
option,
index
})}>
<Box
display="flex"
justifyContent="space-between"
width="100%">
<Box>
<Typography color="textPrimary">
{option.title}
</Typography>
<Typography variant="caption" color="textSecondary">
{option.type}
</Typography>
</Box>
<Box alignSelf="flex-end">
<Typography variant="caption" color="textSecondary">
/components/button
</Typography>
</Box>
</Box>
</Item>
))}
</List>
</Results>
) : null}
</Container>
</BackdropOverlay>
</React.Fragment>
);
}
这是我存储在 results 属性中的 API 响应:
0: {id: 1, title: "Button", slug: "button"}
1: {id: 2, title: "Switch", slug: "switch"}
2: {id: 3, title: "Tags", slug: "tags"}
3: {id: 4, title: "Checkbox", slug: "checkbox"}
4: {id: 5, title: "Toast", slug: "toast"}
【问题讨论】:
-
你能在你的问题中记录
resultsprops 的值吗? -
@NearHuscarl 我添加了它:)
标签: reactjs material-ui next.js