React Async中deferFn与promiseFn的区别及下拉框数据更新选型
Answer: Use
deferFn for Your Dropdown-Textfield Scenario Let’s break this down clearly based on how react-async’s Async component behaves:
Key Differences Between promiseFn and deferFn
promiseFn: Runs immediately when the component mounts, even if the user hasn’t interacted with the textfield yet. While it will trigger on input changes too, that initial mount execution is unnecessary for a dropdown that should only load data when the user starts typing—you’ll end up with an extra, likely empty query request right off the bat.deferFn: Does not run on component mount—it only executes when you explicitly trigger it via therunmethod provided by theAsynccomponent’s render props. This aligns perfectly with your dropdown’s needs: you want to fetch data only when the user types, and update options in real-time as their input changes.
Example Implementation
Here’s how to set this up with your dropdown-textfield:
import { Async } from "react-async"; const SearchDropdown = () => { // Handle input changes and trigger data fetch const handleInputChange = (e, { run }) => { const inputValue = e.target.value; // Pass the latest input value to deferFn via run() run(inputValue); }; return ( <Async // deferFn uses the input value passed from run() to fetch matching options deferFn={(inputValue) => fetch(`/api/dropdown-options?query=${encodeURIComponent(inputValue)}`) .then(res => res.json()) } > {({ data, error, isLoading, run }) => ( <div> <input type="text" onChange={(e) => handleInputChange(e, { run })} placeholder="Type to search..." /> {isLoading && <p>Loading options...</p>} {error && <p>Oops, failed to load options: {error.message}</p>} {data && data.length > 0 && ( <ul className="dropdown-options"> {data.map(option => ( <li key={option.id}>{option.label}</li> ))} </ul> )} </div> )} </Async> ); };
Why This Works
- No unnecessary initial requests:
deferFnwaits until the user starts typing before fetching data, which is more efficient and avoids showing irrelevant empty-state content. - Real-time sync: Every input change triggers
run(), which executesdeferFnwith the latest input value—ensuring your dropdown options stay perfectly in sync with what the user is typing.
Using promiseFn would force you to add extra logic to suppress that initial mount request, adding unnecessary complexity. deferFn is the clean, intended solution for this kind of user-triggered data fetching.
内容的提问来源于stack exchange,提问作者Tamas Bogdan
相关产品推荐
相关产品推荐

