提问人:Vlad Suciu 提问时间:10/28/2023 更新时间:10/28/2023 访问量:23
React 自定义钩子获取数据返回之前搜索到的值
React custom hook to fetch data returns previous searched value
问:
“resolveOptions”中的 console.log 将始终显示上一个搜索的服务器结果,但 useEffect 中的 console.log 将显示正确的当前服务器结果。需要进行哪些更改才能确保“resolveOptions”具有正确的结果?
export const MyComponent = () => {
const { data, getData } = usePromise();
const usePromise = () => {
const [searchValue, setSearchValue] = useState<string>();
const dataRef = useRef<string[]>();
const { results } = useHookToFetchDataFromServer({ filter: { field: searchValue} });
useEffect(() => {
if (results) {
const items = results.items.map(item => item.label);
dataRef.current = items;
console.log(dataRef.current); // logs the correct value received from the server based on the 'search string'
}
}, [results]);
const getData = (searchVal: string) => {
setSearchValue(searchVal);
};
return {
data: new Promise<string[]>(resolve => resolve(dataRef.current)),
getData
};
}
const resolveOptions = (search: string): Promise<string[]> => {
getData(search);
data.then(res => console.log(res)); // will log the previous results from the server (e.g. If I search for A, then for B, instead of showing results for B it will show results for A)
return prom;
}
return (<MyChildComponent optionsResolver={resolveOptions}/>);
}
答: 暂无答案
评论