【问题标题】:Inside useEffect is never run in react-redux application内部 useEffect 永远不会在 react-redux 应用程序中运行
【发布时间】:2019-05-05 17:48:09
【问题描述】:

我有以下组件。我做了调试。 useEffect 中的函数永远不会被调用。代码到达useEffect,但没有进入内部,因此不会从数据库中获取记录。任何想法为什么会发生这种情况?

import * as React from 'react';
import { useEffect } from 'react';
import { connect } from 'react-redux';
import { FetchAssignmentData } from './AssignmentDataOperations'

const AssignmentComprehensive = (props) => {

    useEffect(() => {
        if (props.loading != true)
            props.fetchAssignment(props.match.params.id);
    }, []);

    if (props.loading) {
        return <div>Loading...</div>;
    }

    if (props.error) {
        return (<div>{props.error}...</div>)
    }

    //these are always null
    const assignmentId = props.assignmentIds[0];
    const assignment = props.assignments[assignmentId];

    return (
        //this throws error since the values are never fetched from db
        <div>{props.assignments[props.assignmentIds[0]].title}</div>
    );
}

const mapStateToProps = state => ({
    assignmentIds: state.assignmentReducer.assignmentIds,
    assignments: state.assignmentReducer.assignments,
    submissions: state.assignmentReducer.submissions,
    rubric: state.assignmentReducer.rubric,
    loading: state.assignmentReducer.loading,
    error: state.assignmentReducer.error
})

const mapDispatchToProps = dispatch => {
    return { fetchAssignment: (id) => dispatch(FetchAssignmentData(id)) };
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(AssignmentComprehensive);

【问题讨论】:

    标签: reactjs redux react-redux react-hooks


    【解决方案1】:

    因为useEffect第二个参数:

    https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

    如果你想运行一个效果并且只清理一次(在挂载和卸载时),你可以传递一个空数组([])作为第二个参数。这告诉 React 你的效果不依赖于任何来自 props 或 state 的值,所以它永远不需要重新运行。

    所以它只运行一次(当props.loadingtrue 时)并且再也不会运行。

    您似乎有 3 个依赖项:

    useEffect(() => {
      ...
    }, [props.loading, props.fetchAssignment, props.match.params.id])
    

    另请参阅:react-hooks/exhaustive-depseslint rule

    【讨论】:

    • @renakre 是的,情况总是如此。您应该随时准备渲染,您无法停止它。因此你应该总是返回一些 JSX。您可以从加载状态开始,然后在获取完成后呈现结果,我相信这就是您在这里所做的,完全没问题。
    • @renakre 正确,因此您应该渲染其他内容。 (获取数据时的加载状态)显然不依赖于数据的东西。像&lt;div&gt;Loading...&lt;/div&gt; 这样的东西,一旦你有了数据&lt;div&gt;{props.data}&lt;/div&gt;
    • &lt;div&gt;Loading...&lt;/div&gt; 已经在 OP 中,我相信将 useEffect 的第二个参数从 [] 编辑到我的建议应该可以工作......也许第三个需要更具防御性:@987654334 @
    • @Aprillion 这是一个很好的快速修复。但我认为他很困惑,因为他想在返回 JSX 之前做点别的事情,这是因为他需要了解 SPA 和异步渲染的基础知识。
    • @renakre 这是 Dan Abramov 写的非常好的blog 我认为每个 React 开发人员都应该阅读。如果您没有时间阅读这个part,它解决了这个问题。
    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 2016-08-20
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    相关资源
    最近更新 更多