相关疑难解决方法(0)

使React useEffect挂钩不在初始渲染上运行

根据文件:

componentDidUpdate()更新发生后立即调用.初始渲染不会调用此方法.

我们可以使用新的useEffect()钩子来模拟componentDidUpdate(),但似乎useEffect()是在每次渲染之后运行,甚至是第一次.如何让它不能在初始渲染上运行?

正如您在下面的示例中所看到的,componentDidUpdateFunction在初始渲染期间打印,但componentDidUpdateClass在初始渲染期间未打印.

function ComponentDidUpdateFunction() {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    console.log("componentDidUpdateFunction");
  });

  return (
    <div>
      <p>componentDidUpdateFunction: {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

class ComponentDidUpdateClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  componentDidUpdate() {
    console.log("componentDidUpdateClass");
  }

  render() {
    return (
      <div>
        <p>componentDidUpdateClass: {this.state.count} times</p>
        <button
          onClick={() => { …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

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

React Hooks-即使状态未更改,也会触发useEffect

我在组件内部设置了一个效果,如果另一个状态属性发生更改,该效果也会更改视图。但是由于某种原因,即使安装了该组件,该组件的效果仍会运行,即使的值detailIndex没有更改。

const EventsSearchList = () => {
    const [view, setView] = useState('table');
    const [detailIndex, setDetailIndex] = useState(null);

    useEffect(() => {
        console.log('onMount', detailIndex);
        // On mount shows "null"
    }, []);


    useEffect(
        a => {
            console.log('Running effect', detailIndex);
            // On mount shows "null"!! Should not have run...
            setView('detail');
        },
        [detailIndex]
    );

    return <div>123</div>;

};
Run Code Online (Sandbox Code Playgroud)

为什么会这样呢?

更新:如果不清楚,我正在尝试的是在组件更新时运行效果,因为detailIndex更改了。挂载时不行。

reactjs react-hooks

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

标签 统计

react-hooks ×2

reactjs ×2

javascript ×1