【问题标题】:Dispatch redux action after apollo-react query在 apollo-react 查询后调度 redux 操作
【发布时间】:2018-02-16 01:32:21
【问题描述】:

我想在查询完成后立即分派一个 redux 操作。 – 哪里是合适的地方?

这里我保留了对refetch 函数的引用,以便以后可以轻松地使用最新数据更新视图。

export default graphql(
    allFilesQuery,
    {
        props: ({ ownProps, data }) => {
            const { dispatch } = ownProps;
            dispatch(
                setRefetchAllFiles(data.refetch)
            );
            return {
                data,
                ...ownProps,
            };
        }
    }
)(FileListComponent);

虽然这有效,但我也收到警告,说:

Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

【问题讨论】:

    标签: redux react-apollo


    【解决方案1】:

    props 函数应该是纯函数并返回 props 以注入组件,而不会执行任何副作用。实际上,您可以通过将您的调度包装在setTimeout 中来进行调度,但这将是一个非常糟糕的主意,因为每次您的组件重新渲染时都会运行props 函数,并且可能会触发许多不需要的调度.如果您的调度使组件重新渲染,它甚至可能导致无限循环。

    做你想做的事的正确位置是在你的组件中。您可以使用componentWillReceiveProps(或其他生命周期),并将前一个道具与下一个道具进行比较,在适当的时候触发调度。为此,您可以使用data.networkStatusdata.loading

    【讨论】:

      猜你喜欢
      • 2017-12-27
      • 2017-11-09
      • 2017-04-07
      • 2017-12-04
      • 1970-01-01
      • 2018-02-09
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多