简体   繁体   English

为什么功能块内的 useState 值为 null?

[英]Why is useState value null inside function block?

I know there is a scoping issue here.我知道这里有一个范围界定问题。 I just can't find it.我就是找不到。 Why is 'items' null in the searchItems() block?为什么searchItems()块中的“items”为空?

export const useStore = () => {
   const [items, setItems] = useState(null)

   const setItemsFromApi = () => {
      //call api to get data, then
      setItems(data)
   }

   const searchItems = (query) => {
      //use the local data and filter based on query
      //'items' IS NULL IN THIS SCOPE
      items.filter(() => {})
   }

   console.log(items) // 'items' HAS UPDATED VALUE AFTER setItemsFromApi() IN THIS SCOPE

   return {setItemsFromApi, searchItems}
}

Use store like this.像这样使用商店。 (NOTE: I left out the rendering of the items in the list because that part works fine. Just focusing on why the onClick doesn't use the already loaded items to filter with.) (注意:我省略了列表中项目的渲染,因为该部分工作正常。只关注为什么 onClick 不使用已加载的项目进行过滤。)

export default function DataList(props) => {     
   const store = useStore();

   useEffect(() => {
      store.setItemsFromApi()
   }, [])
    
   const runSearch = (query) => {
      store.searchItems(query)
   }

   return <button onClick={runSearch('searchTerm')}   
 }

I even tried passing it as a callback dependency, but it's still null我什至尝试将其作为回调依赖项传递,但它仍然为空

const searchItems = useCallback((query) => {
    //'items' IS STILL NULL IN THIS SCOPE
    items.filter(() => {})
 }, [items])

From the code you posted,从您发布的代码中,

const store = useStore() store.setItemsFromApi() ... store.searchItems(query) const store = useStore() store.setItemsFromApi() ... store.searchItems(query)

the issue may be because you are doing an async operation (calling the API), but the search is not waiting for the result of the fetch call.问题可能是因为您正在执行异步操作(调用 API),但搜索并未等待 fetch 调用的结果。 So, when you do the所以,当你做

store.searchItems(query) store.searchItems(查询)

, the store is null and only changes its value later. , store 为 null 并且仅在稍后更改其值。

In a nutshell, the state wasn't refreshing after triggering a search because I had a "debounce" useRef function running within the component when the onChange event was fired, even though this was a local data search.简而言之,触发搜索后状态没有刷新,因为当 onChange 事件被触发时,我在组件内运行了一个“去抖动” useRef函数,即使这是一个本地数据搜索。 I guess this interrupted the re-render event.我猜这中断了重新渲染事件。 So I moved the debounce directly to the api service call for when search requires an api call.因此,当搜索需要 api 调用时,我将 debounce 直接移至 api 服务调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM