[英]Fetching data from server in Remix.run
I was exploring Remix.run and making a sample app.我正在探索Remix.run并制作一个示例应用程序。 I came across an issue that has been bothering me for some time now.
我遇到了一个困扰我一段时间的问题。 Correct me if I am wrong:
action()
is for handling Form submission, and loader()
is for fetching data initially.如果我错了,请纠正我:
action()
用于处理表单提交,而loader()
用于最初获取数据。 For my application, I used mongoose to connect MongoDB, defined models, and defined querying function in a query.server.ts
file.对于我的应用程序,我使用 mongoose 连接 MongoDB,定义模型,并在
query.server.ts
文件中定义查询 function。 I want to fetch data from the database through a function defined in the query.server.ts
file when an image is clicked on the UI.当在 UI 上单击图像时,我想通过 q
query.server.ts
文件中定义的 function 从数据库中获取数据。 How can I do that without using forms?如果不使用 forms,我该怎么做? I cannot pre-fetch the data without knowing what image was clicked by the user.
我无法在不知道用户点击了什么图像的情况下预取数据。
You can create a resource route.您可以创建资源路由。 These are like regular routes, but don't export a default component (no UI).
这些类似于常规路由,但不导出默认组件(无 UI)。
You can use the useFetcher
hook and call fetcher.load()
to call your resource route.您可以使用
useFetcher
挂钩并调用fetcher.load()
来调用您的资源路由。 The data is in fetcher.data
.数据在
fetcher.data
中。
// routes/query-data.ts
export const loader: LoaderFunction = async ({request}) => {
const url = new URL(request.url)
const img = url.searchParams.get('img')
const data = await getData(img)
return json(data)
}
// routes/route.tsx
export default function Route() {
const fetcher = useFetcher()
const handleImgClick = (e) => {
const img = e.target
fetcher.load(`/query-data?img=${img.attr('src')}`)
}
return (
<div>
<img onClick={handleImageClick} src="/images/file.jpg" />
<pre>{ JSON.stringify(fetcher.data, null, 2) }</pre>
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.