标签: react-hooks

React.useState不会从props重新加载状态

我期望状态在道具更改时重新加载,但这不起作用,并且user变量在下次useState调用时不会更新,这是怎么回事?

function Avatar(props) {
  const [user, setUser] = React.useState({...props.user});
  return user.avatar ? 
         (<img src={user.avatar}/>)
        : (<p>Loading...</p>);
}
Run Code Online (Sandbox Code Playgroud)

码笔

reactjs react-hooks

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

useState挂钩设置器错误地覆盖了状态

问题出在这里:我试图在单击按钮时调用2个函数。这两个函数都会更新状态(我正在使用useState挂钩)。第一个函数将value1正确更新为'new 1',但是在1s(setTimeout)之后触发,第二个函数将值2更改为'new 2',但是!它将value1设置回'1'。为什么会这样呢?提前致谢!

import React, { useState } from "react";

const Test = () => {
  const [state, setState] = useState({
    value1: "1",
    value2: "2"
  });

  const changeValue1 = () => {
    setState({ ...state, value1: "new 1" });
  };
  const changeValue2 = () => {
    setState({ ...state, value2: "new 2" });
  };

  return (
    <>
      <button
        onClick={() => {
          changeValue1();
          setTimeout(changeValue2, 1000);
        }}
      >
        CHANGE BOTH
      </button>
      <h1>{state.value1}</h1>
      <h1>{state.value2}</h1>
    </>
  );
};

export default Test;
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

30
推荐指数
3
解决办法
1210
查看次数

如何在反应中处理自定义钩子的依赖项数组

我正在创建一个自定义钩子,并想定义一个可选参数,以便我可以在需要时传入额外的依赖项。我的代码如下所示:

import { useEffect } from 'react';

function useCustomHook(param1, extraDeps) {
  useEffect(() => {
    // do something with param1 here
  }, [param1, ...extraDeps])
}
Run Code Online (Sandbox Code Playgroud)

react-hooks/exhaustive-deps 发出警告说

React Hook useEffect 在其依赖数组中有一个 spread 元素。这意味着我们无法静态验证您是否传递了正确的依赖项

任何人都知道如何解决该警告?或者将 deps 数组传递给自定义钩子不是一个好习惯?

对于那些对为什么需要 extraDeps 感兴趣的人。这是一个例子:

const NewComponent = (props) => {
  [field1, setField1] = useState()
  [field2, setField2] = useState()

  // I only want this to be called when field1 change
  useCustomHook('.css-selector', [field1]);

  return <div>{field1}{field2}</div>;
}
Run Code Online (Sandbox Code Playgroud)

reactjs react-hooks

29
推荐指数
2
解决办法
9246
查看次数

为什么我们要在没有依赖数组的情况下使用 useEffect?

我有这个代码:

const App: React.FC = () => {
  const [isOpen, setIsOpen] = React.useState(true);
  const [maxHeight, setMaxHeight] = React.useState();

  const wrapper = React.useRef<HTMLDivElement>(null);
  const content = React.useRef<HTMLDivElement>(null);

  const setElementMaxHeight = () => {
    if (content && content.current) {
      setMaxHeight(isOpen ? content.current.offsetHeight : 0);
    }
  };

  useEffect(() => {
   setElementMaxHeight();

    window.addEventListener("resize", setElementMaxHeight);

    return () => {
      window.removeEventListener("resize", setElementMaxHeight);
    };
  });

  const toggle = () => {
    setIsOpen(!isOpen);
  };

  return (
    <div>
      <button onClick={toggle}>
        <span className="nominal-result__expander fa" />
      </button>
      <div
        className="nominal-results__list-wrapper"
        ref={wrapper}
        style={!!maxHeight …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

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

类型错误:组件不是添加forwardRef的函数

您好,我试图将forwardRef添加到子组件,但在添加forwardRef时得到以下信息: TypeError: Component is not a function

该组件定义如下:

import React from 'react';
import { forwardRef } from 'react';
import { TextInputFocusEventData } from 'react-native';
import { NativeSyntheticEvent, StyleSheet } from 'react-native';
import { Input, InputProps } from 'react-native-elements';
import { Metrics, Colors } from '../../theme';
import Icons from '../Icons';


const CustomTextInput2 = forwardRef<TextInput, ICustomtextnputProps>((props, ref) => {
    const { name, required } = props;

    return (
        <Input
            rightIcon={<Icons name="right" />}
            placeholder={name?.concat(required ? '*' : '')}
            inputContainerStyle={styles.inputContainer}
            inputStyle={styles.inputText}
            {...props}
        />
    ) …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-native react-hooks react-forwardref

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

在使用挂钩时,React是否批量状态更新功能?

对于类组件,this.setState如果在事件处理程序内部则调用批处理.但是如果在事件处理程序之外更新状态并使用'useState'钩子会发生什么?

function Component() {
  const [a, setA] = useState('a');
  const [b, setB] = useState('b');

  function handleClick() {
    Promise.resolve().then(() => {
      setA('aa');
      setB('bb');
    });
  }

  return <button onClick={handleClick}>{a}-{b}</button>
}
Run Code Online (Sandbox Code Playgroud)

它会useState马上渲染吗?或者它会是aa - bb然后aa - b呢?

reactjs react-hooks

28
推荐指数
4
解决办法
4663
查看次数

使用useEffect,如何跳过对初始渲染应用效果?

使用React的新效果钩子,如果重新渲染之间某些值没有改变,我可以告诉React跳过应用效果 - 来自React的文档示例:

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
Run Code Online (Sandbox Code Playgroud)

但是上面的例子应用了初始渲染时的效果,以及后续重新渲染的位置count.如何告诉React跳过初始渲染的效果?

reactjs react-hooks

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

我在哪里可以使用钩子进行API调用?

基本上我们componentDidMount()在React类组件中的生命周期方法中进行API调用,如下所示

     componentDidMount(){
          //Here we do API call and do setState accordingly
     }
Run Code Online (Sandbox Code Playgroud)

但是在React v16.7.0中引入了钩子之后,就没有更多的类组件了.

我的查询是,我们究竟需要在带有钩子的功能组件中进行API调用?

我们有类似的方法componentDidMount()吗?

javascript reactjs react-native react-hooks

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

useState是同步的吗?

过去,我们曾明确警告过调用setState({myProperty})是异步的,并且this.state.myProperty直到回调或下一个render()方法才有效。

使用useState,如何在显式更新状态后获取状态的值?

钩子如何工作?据我所知,setter函数useState不接受回调,例如

const [value, setValue] = useState(0);
setValue(42, () => console.log('hi callback');
Run Code Online (Sandbox Code Playgroud)

不会导致回调运行。

在旧世界中,我的另一种解决方法是(e.g. this.otherProperty = 42)在类上挂一个实例变量,但这在这里不起作用,因为没有函数实例可以重用(this在严格模式下不可以)。

javascript reactjs react-hooks

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

反应挂钩useEffect依赖数组

我试图把头缠在新的react钩子api上。具体来说,我正在尝试构建一次经典的用例:

componentDidUpdate(prevProps) {
    if (prevProps.foo !== this.props.foo) {
        // animate dom elements here...
        this.animateSomething(this.ref, this.props.onAnimationComplete);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我尝试使用功能组件和构建相同的组件useEffect,但不知道如何实现。这是我尝试的:

useEffect(() => {
    animateSomething(ref, props.onAnimationComplete);
}, [props.foo]);
Run Code Online (Sandbox Code Playgroud)

这样,仅在props.foo更改时才调用效果。那确实有效–但是!由于将其eslint-plugin-react-hooks标记为错误,因此它似乎是反模式。效果内使用的所有依赖项都应在依赖项数组中声明。因此,这意味着我必须执行以下操作:

useEffect(() => {
    animateSomething(ref, props.onAnimationComplete);
}, [props.foo, ref, props.onAnimationComplete]);
Run Code Online (Sandbox Code Playgroud)

但这不会导致掉毛错误,但完全无法实现props.foo更改时调用效果的目的。我不希望在其他道具或裁判改变时调用它。

现在,我读到一些有关使用useCallback这种包装的信息。我试过了,但没有得到进一步的解决。

有人可以帮忙吗?

javascript reactjs react-hooks

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