【问题标题】:How to load a listbox of states depending on the selected country in RemixRun?如何根据 RemixRun 中选定的国家/地区加载州列表框?
【发布时间】:2022-11-12 14:32:56
【问题描述】:

我喜欢 Remix,但有些事情我想知道它是如何实现的。

假设我有 2 个列表框,一个用于国家,另一个用于州。

根据从上一个列表中选择的国家/地区,我将如何实现各州的加载?

【问题讨论】:

    标签: javascript typescript remix.run


    【解决方案1】:

    这是一个快速演示。我正在使用useFetcher 在国家/地区更改时加载数据。如您所见,我还从加载程序发送了初始数据。

    export const loader: LoaderFunction = async ({ request }) => {
      const url = new URL(request.url)
      const country = url.searchParams.get('country') || 'United States'
      const countries = Object.keys(statesByCountry)
      const states = statesByCountry[country]
    
      return json({ countries, country, states })
    }
    
    export default function Index() {
      const initialData = useLoaderData()
      const fetcher = useFetcher()
      const { countries, country, states } = fetcher.data ?? initialData
    
      const handleChange = (e) => {
        const params = new URLSearchParams()
        params.set('country', e.target.value)
        fetcher.load(`?index&${params.toString()}`)
      }
      return (
        <div className="m-2">
          <h1 className="text-2xl font-bold">Remix Dual Lists!</h1>
          <div className="flex gap-4">
            <select
              name="country"
              defaultValue={country}
              onChange={handleChange}
              size={10}
            >
              {countries.map((country) => (
                <option>{country}</option>
              ))}
            </select>
            <select name="state" size={10}>
              {states.map((state) => (
                <option>{state}</option>
              ))}
            </select>
          </div>
        </div>
      )
    }
    

    https://codesandbox.io/s/remix-dual-lists-epcxvu?file=/app/routes/index.tsx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多