标签: react-hooks

一起使用 useRef 和forwardRef 的正确方法是什么?

我有两个组件:AppChild。我使用useRefhook 来获取组件中的 DOM 元素Child并对其进行一些处理。

我还使用API在组件之间ref传递。AppChildReact.forwardRef

App.tsx

import { useRef } from "react";
import Child from "./Child";

export default function App() {
  const ref = useRef(null);
  console.log("App ref: ", ref);
  return (
    <div className="App">
      <Child ref={ref} />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

Child.ts

import React, { useEffect, useRef } from "react";

export default React.forwardRef((props, ref) => {
  const innerRef = useRef<HTMLDivElement>(null);
  const divElement = ref || innerRef; // …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs react-hooks

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

为什么每次渲染都会调用来自 `useEffect` 的清理函数?

我一直在学习 React,我读到从返回的函数useEffect是为了进行清理,而 React 在组件卸载时执行清理。

因此,我对其进行了一些试验,但在以下示例中发现,每次组件重新渲染时都会调用该函数,而不是仅在从 DOM 卸载时调用该函数,即每次组件重新渲染时都会调用该函数console.log("unmount");

这是为什么?

function Something({ setShow }) {
  const [array, setArray] = useState([]);
  const myRef = useRef(null);

  useEffect(() => {
    const id = setInterval(() => {
      setArray(array.concat("hello"));
    }, 3000);
    myRef.current = id;
    return () => {
      console.log("unmount");
      clearInterval(myRef.current);
    };
  }, [array]);

  const unmount = () => {
    setShow(false);
  };

  return (
    <div>
      {array.map((item, index) => {
        return (
          <p key={index}>
            {Array(index + 1)
              .fill(item)
              .join("")}
          </p>
        );
      })}
      <button onClick={() => …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks use-effect

40
推荐指数
1
解决办法
3万
查看次数

当Reducer 中的store 发生变化时,useSelector 不会更新。ReactJS Redux

我正在改变减速机的状态。在调试时,我检查了状态是否真的改变了。但是组件没有更新。

成分:

function Cliente(props) {
    const dispatch = useDispatch()
    const cliente = useSelector(({ erpCliente }) => erpCliente.cliente)
    const { form, handleChange, setForm } = useForm(null)

...

function searchCepChangeFields() {
    //This call the action and change the store on reducer
    dispatch(Actions.searchCep(form.Cep))  
        .then(() => {   
            // This function is only taking values ??from the old state. 
            // The useSelector hook is not updating with store
            setForm(form => _.setIn({...form}, 'Endereco', cliente.data.Endereco))
            setForm(form => _.setIn({...form}, 'Uf', cliente.data.Uf))
            setForm(form => _.setIn({...form}, 'Cidade', cliente.data.Cidade))
            setForm(form => …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 reactjs react-redux react-hooks

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

`useRef`和`createRef`有什么区别?

当我偶然发现时,我正在浏览钩子文档useRef.

看看他们的例子......

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

......好像useRef可以换成createRef.

function TextInputWithFocusButton() {
  const inputRef = createRef(); // what's the diff?
  const onButtonClick = () => {
    // `current` points to the mounted text input element
    inputRef.current.focus();
  };
  return (
    <>
      <input ref={inputRef} …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

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

清除 React Hooks 中未安装组件的内存泄漏

我是使用 React 的新手,所以这可能很容易实现,但即使我做了一些研究,我也无法自己弄清楚。如果这太愚蠢,请原谅我。

语境

我将Inertia.js与 Laravel(后端)和 React(前端)适配器一起使用。如果你不知道惯性,它基本上是:

Inertia.js 可让您使用经典的服务器端路由和控制器快速构建现代单页 React、Vue 和 Svelte 应用程序。

问题

我正在做一个简单的登录页面,它有一个表单,提交时将执行 POST 请求以加载下一页。它似乎工作正常,但在其他页面中,控制台显示以下警告:

警告:无法对卸载的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消 useEffect 清理函数中的所有订阅和异步任务。

在登录中(由 Inertia 创建)

相关代码(我已经对其进行了简化以避免不相关的行):

import React, { useEffect, useState } from 'react'
import Layout from "../../Layouts/Auth";

{/** other imports */}

    const login = (props) => {
      const { errors } = usePage();

      const [values, setValues] = useState({email: '', password: '',});
      const [loading, setLoading] = useState(false);

      function handleSubmit(e) {
        e.preventDefault();
        setLoading(true);
        Inertia.post(window.route('login.attempt'), values)
          .then(() => {
              setLoading(false); …
Run Code Online (Sandbox Code Playgroud)

javascript promise inertiajs reactjs react-hooks

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

反应笑话模拟 useNavigate()

"react-router-dom": "^6.0.0-alpha.5",
Run Code Online (Sandbox Code Playgroud)

我几乎尝试了一切。

我只是想从钩子上模拟这个navigate()调用useNavigate()。就是这样。简单的。没有任何作用。

不,我不想使用Link。useNavigate 也在其他地方以编程方式使用,我也想模拟它们

"react-router-dom": "^6.0.0-alpha.5",
Run Code Online (Sandbox Code Playgroud)

我已经尝试过这些:

jest.mock('react-router-dom', () => {
    // Require the original module to not be mocked...
    const originalModule = jest.requireActual('react-router-dom');

    return {
        __esModule: true,
        ...originalModule,
        // add your noops here
        useNavigate: jest.fn(() => 'bar')
    };
});
Run Code Online (Sandbox Code Playgroud)
import * as ReactRouterDom from "react-router-dom";
...
// cannot redefine property
          Object.defineProperty(ReactRouterDom, 'useNavigate', {
              configurable: true,
              value: jest.fn(() => 'bar')
          });
Run Code Online (Sandbox Code Playgroud)
// doesnt work
          jest.mock('react-router-dom', () => ({
              useNavigate: jest.fn(() => jest.fn), …
Run Code Online (Sandbox Code Playgroud)

mocking reactjs jestjs react-router-dom react-hooks

39
推荐指数
3
解决办法
5万
查看次数

我该如何在React中强制使用钩子重新渲染组件?

考虑下面的钩子示例

   import { useState } from 'react';

   function Example() {
       const [count, setCount] = useState(0);

       return (
           <div>
               <p>You clicked {count} times</p>
               <button onClick={() => setCount(count + 1)}>
                  Click me
               </button>
          </div>
        );
     }
Run Code Online (Sandbox Code Playgroud)

基本上,我们使用this.forceUpdate()方法强制组件在React类组件中立即重新呈现,如下例所示

    class Test extends Component{
        constructor(props){
             super(props);
             this.state = {
                 count:0,
                 count2: 100
             }
             this.setCount = this.setCount.bind(this);//how can I do this with hooks in functional component 
        }
        setCount(){
              let count = this.state.count;
                   count = count+1;
              let count2 = this.state.count2;
                   count2 = count2+1;
              this.setState({count});
              this.forceUpdate();
              //before below …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-native react-hooks

38
推荐指数
11
解决办法
3万
查看次数

React Dev Tools:“解析钩子名称”操作引发“钩子解析失败”错误

当我使用反应开发工具检查我的代码时,我注意到一些钩子触发了此错误并导致“解析钩子名称”操作出错。当我检查反应开发工具时,它输出:

main.js:4878 Error: Could not find runtime location for line:177321 and column:81
    at Object.originalPositionFor
Run Code Online (Sandbox Code Playgroud)

Facebook/React issues 上的这个线程来看,它似乎可能与 webpack 源映射相关。有人对可能导致这种情况的原因有任何想法吗?这种情况不仅发生在自定义挂钩中,而且发生在我的代码库中的标准useStateusecallback挂钩中。

反应开发工具 反应开发工具错误

编辑:我尝试了devtool具有多个值的 webpack 设置,但问题仍然存在。该问题目前在我的代码库上已经消失,但它间歇性地出现,使其难以重现。在有确凿证据解释造成这种情况的原因之前,请不要提出任何问题。

javascript reactjs react-devtools react-hooks

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

带有 React Hooks 的 Firebase 侦听器

我想弄清楚如何使用 Firebase 侦听器,以便使用 React 挂钩更新来刷新云 Firestore 数据。

最初,我使用带有 componentDidMount 函数的类组件来获取 firestore 数据。

this.props.firebase.db
    .collection('users')
    // .doc(this.props.firebase.db.collection('users').doc(this.props.firebase.authUser.uid))
.doc(this.props.firebase.db.collection('users').doc(this.props.authUser.uid))
.get()
.then(doc => {
    this.setState({ name: doc.data().name });
    // loading: false,
  });  
}
Run Code Online (Sandbox Code Playgroud)

当页面更新时会中断,所以我试图弄清楚如何移动侦听器以响应钩子。

我已经安装了react-firebase-hooks工具 - 尽管我不知道如何阅读说明才能让它工作。

我有一个功能组件如下:

import React, { useState, useEffect } from 'react';
import { useDocument } from 'react-firebase-hooks/firestore';

import {
    BrowserRouter as Router,
    Route,
    Link,
    Switch,
    useRouteMatch,
 } from 'react-router-dom';
import * as ROUTES from '../../constants/Routes';
import { compose } from 'recompose';
import { withFirebase } from …
Run Code Online (Sandbox Code Playgroud)

javascript firebase reactjs google-cloud-firestore react-hooks

36
推荐指数
3
解决办法
2万
查看次数

反应自定义钩子与普通函数,有什么区别

我正试图将我的头包裹在自定义钩子上。我理解普通钩子很好,但我的问题是,在编写自定义钩子时,它与普通函数有什么区别?我的意思是为什么不称其为普通函数而不是将其称为 use*

reactjs react-hooks

35
推荐指数
5
解决办法
6018
查看次数