reactjs - React router 卸载功能组件

标签 reactjs react-router react-router-v4 react-hooks

我正在使用 React Router,并且有两条渲染相同组件的路由:

<Switch>
    <Route path="/aaa" component={Cmp} />
    <Route path="/bbb" component={Cmp} />
</Switch>

这是 Cmp 实现:

class Cmp extends Component {
    componentWillUnmount() {
        console.log('******************* UNMOUNTED');
    }

    render() {
        return null;
    }
}

正如我所料,在 /aaa/bbb 之间导航不会卸载 Cmp。

我正在转向钩子(Hook),所以我重写了组件:

function Cmp() {
    useEffect(() => {
        return () => {
            console.log('******************* UNMOUNTED');
        };
    });

    return null;
}

非常令人惊讶的是,运行应用程序时,在 /aaa/bbb console.log 之间导航,发现 Cmp 已卸载。
知道如何使用函数组件和钩子(Hook)来防止不必要的卸载安装吗?

最佳答案

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works. ...read more

现在,每次重新渲染 Cmp 组件时都会调用您的效果。如果您只想在卸载时调用效果,则必须将带有空数组的第二个参数传递给 useEffect:

useEffect(() => {
    return () => {
        console.log('******************* UNMOUNTED');
    };
}, []);

关于reactjs - React router 卸载功能组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56150069/

相关文章:

java - 错误 : org. hibernate.PersistentObjectException:分离的实体传递给持久化

javascript - onClick触发点击报错: current.点击不是函数

reactjs - 我尝试将 Material-UI RaisingButton 链接到外部 url 但没有成功?

javascript - React SVG,结合 SVG 的问题

reactjs - 创建 react 应用程序,重新加载不起作用

javascript - 如何导入或仅使用子组件?

reactjs - React router 4 不会更新链接上的 View ,但会在刷新时更新

reactjs - this.props.history.push 不重新渲染 react 组件

javascript - 获取后导航到 React 组件中包含数据的另一个页面

javascript - React router dom 库不适用于我的项目