标签: react-custom-hooks

如果自定义钩子内部的状态发生变化,组件会重新渲染吗?

在我的 React 应用程序中,我有一个自定义钩子,它useState在内部保存一个值,但自定义钩子本身不返回任何值。

如果其内部的值发生useState变化,这是否会导致调用此自定义挂钩的组件重新渲染?

reactjs react-hooks use-state react-custom-hooks

9
推荐指数
1
解决办法
7042
查看次数

useMutation 状态始终为“idle”且“isLoading”始终为“false”-react-query

所以我使用react-query来处理API请求。当前的问题是,当我尝试提交表单数据、发布请求时,突变状态始终处于空闲状态,并且加载始终为 false。我还使用 zustand 进行状态管理。

这是 useSubmitFormData 挂钩。Post 请求按预期执行,只是突变状态和 isLoading 没有改变。

export const useSubmitFormData = () => {
  const { postDataPlaceholder } = usePlaceholderApi();
  // data which is submiting is getting from the store - reducer
  const { data, filesToUpload } = useFormDataStore();

  const { mutate, status, isLoading } = useMutation(() => postDataPlaceholder({ data }), {
    onMutate: () => console.log('onMutate', status),
    onSuccess: (res) => console.log(res),
    onError: (err) => console.log('err', err),
  });

  return {
    submitForm: mutate,
    isLoading,
  };
};
Run Code Online (Sandbox Code Playgroud)

现在在 FormPage.jsx 上它是这样触发的: …

reactjs axios react-hooks react-query react-custom-hooks

7
推荐指数
1
解决办法
4401
查看次数

在 Typescript 中将类型作为参数传递

我编写了一个自定义挂钩来帮助我不重复某些获取调用的代码。它看起来像这样:

export const useCustomQuery = ({ endpoint, body, dataPoint }: args) => {
    const [data, setData] = useState()
    useEffect(() => {
        fetch(`http://localhost:4000/${endpoint}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body,
        })
            .then((res) => res.json())
            .then((res) => {
                if (dataPoint) {
                    setData(JSON.parse(res.data[dataPoint]))
                }
            })
    }, [endpoint, body, dataPoint])

    return { data }
}
Run Code Online (Sandbox Code Playgroud)

但我收到一些 TS 错误,抱怨数据类型。是否可以将类型作为参数传递,因为调用钩子的每个组件可能会有所不同?或者解决这个问题的最佳方法是什么?

javascript typescript reactjs react-hooks react-custom-hooks

4
推荐指数
1
解决办法
2万
查看次数

测试自定义挂钩 - 未包含在行为警告中

我尝试测试自定义挂钩,但收到此警告消息

console.error node_modules/@testing-library/react-hooks/lib/core/console.js:19
    Warning: An update to TestComponent inside a test was not wrapped in act(...).
    
    When testing, code that causes React state updates should be wrapped into act(...):
    
    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */
    
    This ensures that you're testing the behavior the user would see in the browser. 
Run Code Online (Sandbox Code Playgroud)

这是我的自定义钩子

import { useState, useEffect } from 'react'

import io from 'socket.io-client'

import config from './../../../../config'

const useNotificationsSocket = (user) …
Run Code Online (Sandbox Code Playgroud)

testing react-hooks react-custom-hooks

4
推荐指数
1
解决办法
3772
查看次数

<input> 标签上的属性 `reset` 值无效

我收到这个警告:

react-dom.development.js:86 警告:reset标签上的 prop 值无效。要么将其从元素中删除,要么传递一个字符串或数字值以将其保留在 DOM 中。详情请参见https://reactjs.org/link/attribute-behavior

这来自我的自定义挂钩:

import { useState } from 'react'

export const useField = (type) => {
  const [value, setValue] = useState('')

  const onChange = (event) => {
    setValue(event.target.value)
  }

  const reset = () => {
    setValue('')
  }

  return {
    type,
    value,
    onChange,
    reset
  }
}
Run Code Online (Sandbox Code Playgroud)

该钩子在组件中使用:

const CreateNew = (props) => {
  const content = useField('text')
  const author = useField('text')
  const info = useField('text')

  const navigate = useNavigate()

  const handleSubmit = (e) …
Run Code Online (Sandbox Code Playgroud)

html javascript reactjs react-hooks react-custom-hooks

1
推荐指数
1
解决办法
1558
查看次数

如何在自定义 React hook 中使用 Apollo useMutation

我仍然无法理解 Hooks。我经常遇到它抱怨我正在做的问题Invalid hook call
这次,是尝试useMutation在自定义挂钩中使用 Apollo 的挂钩时。
如果有人能告诉我我做错了什么,我将不胜感激。

组件(我在其中调用自定义挂钩)

export default function MyComponent() {

    const { loading, error, data } = useQuery( GET_ORDERS );

    const setOrdersInMetafields = ( orders: Array<OrderModel> ) => {
        metafieldResp = useSetMetafields( { customerId, value: orders, field: 'duplicateOrders' } );
    }

    @useEffect( () => {
        setOrdersInMetafields( orders );
    }, [ orders ] );
}
Run Code Online (Sandbox Code Playgroud)

定制挂钩

export const useSetMetafields( { customerId, value, field }, { customerId: string, value: any, field: string } ) …
Run Code Online (Sandbox Code Playgroud)

reactjs next.js apollo-client react-hooks react-custom-hooks

0
推荐指数
1
解决办法
2314
查看次数

当状态没有改变时,如何在我的反应组件中重新触发自定义钩子?

我有一个用于从服务器获取数据的自定义挂钩。它有3个参数,分别是pageNumber、pageSize和keyword。据我所知,如果我设置一个或多个这些参数,挂钩就会以新状态重新触发。但是在我的组件中,有一个地方当我创建数据时,所以一旦创建它就必须再次获取数据。但其参数(如 pageNumber、pageSize 和 keywords)均未更新。我只需要它再次运行以获取新数据。在不改变状态的情况下,我该如何做到这一点?(在下面的代码中,“Adapter”是一个 Axios 实例)

这是钩子:

const useFetchLists = (
  url = '',
  currentPage = 1,
  selectedPageSize = 10,
  keyword = ''
) => {
  const [items, setItems] = useState([]);
  const [loading, setloading] = useState(false);
  const [totalPage, setTotalPage] = useState(1);
  const [totalItemCount, setTotalItemCount] = useState(0);

  useEffect(() => {
    const fetchListData = async () => {
      try {
        setloading(true);
        await Adapter.get(
          `${url}?pageNumber=${currentPage}&pageSize=${selectedPageSize}&keyword=${keyword}`,
          {}
        ).then((response) => {
          setItems(response.data.items);
          setTotalPage(response.data.totalPages);
          setTotalItemCount(response.data.totalItems);
        });
      } catch (err) {
      } finally {
        setloading(false);
      }
    }; …
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks react-custom-hooks

0
推荐指数
1
解决办法
4158
查看次数