如何通过URL控制React组件

"Can we make this screen shareable via the URL?"

“我们能通过URL分享这个屏幕吗?”

It's a common feature request. Surprisingly, it also leads to one of the most common causes of bugs in React applications.

这是一个常见的功能请求。令人惊讶的是,它也是React应用程序中最常见的错误原因之一。

Take this searchable table. If you've used React before, you've probably built something just like it:

拿这个可搜索的表格来说。如果你以前使用过React,你可能已经构建过类似的东西:

export default function Page() {
 let [search, setSearch] = useState(''); 
 let { data, isPlaceholderData } = useQuery({ 
 queryKey: ['people', search],
 queryFn: async () => {
 let res = await fetch(`/api/people?search=${search}`); 
 let data = await res.json();

 return data;
 },
 placeholderData: (previousData) => previousData, 
 });

 return (
 <>
 <Heading>Your team</Heading>

 <InputGroup>
 {isPlaceholderData ? <Spinner /> : <MagnifyingGlassIcon />}
 
 <Input
 value={search} 
 onChange={(e) => setSearch(e.target.value)} 
 placeholder="Find someone..."
 />
 </InputGroup>

 {!data ? (
 <Spinner />
 ) : (
 <Table>
 <TableHead>
 <TableRow>
 <TableHeader>Name</TableHeader>
 <TableHeader>Email</TableHeader>
 <TableHeader>Role</TableHeader>
 </TableRow>
 </TableHead>
 <TableBody>
 {data.people.map((person) => ( 
 <TableRow key={person.id}>
 <TableCell>{person.name}</TableCell>
 <TableCell>{person.email}</TableCell>
 <TableCell>{person.role}</TableCell>
 </TableRow> 
 ))}
 </TableBody>
 </Table>
 )}
 </>
 );
}

It's built using React Query to fetch the table's data from the server, and it has an input that updates some local React state, which re-fires the query to fetch new search results for the table.

它是使用React Query构建的,从服务器获取表格数据,并且它有一个input,它会更新一些本地的React状态,这将重新触发查询以获取表格的新搜索结果。

And it works great! But our table isn't shareable.

而且它工作得很好!但是我们的表格不能共享。

Try typing in "john", then hitting Reload:

尝试输入"john",然后点击重新加载:

Poof!

噗!

Since all our state is in React, the search text and table data don't survive page reloads.

由于我们所有的状态都在React中,搜索文本和表格数据在页面重新加载时不会保留。

And this is where the feature request comes in:

这就是功能请求的用途:

"Can we make this screen shareable...

开通本站会员,查看完整译文。

Home - Wiki
Copyright © 2011-2024 iteam. Current version is 2.139.0. UTC+08:00, 2024-12-22 18:46
浙ICP备14020137号-1 $Map of visitor$