繁体   English   中英

如何在 react.js 中检测父组件中的子渲染

[英]How to detect child renders in a parent component in react.js

我正在尝试缓存App组件的呈现标记。 我知道这在某种程度上“违反规则”,但我处于无服务器环境(chrome 扩展)中。 在页面加载时,我想将缓存的App标记注入到 DOM 中。 预期的结果类似于在服务器上使用 react-component 渲染器的体验。 非常像这里描述的: http : //www.tabforacause.org/blog/2015/01/29/using-reactjs-and-application-cache-fast-synced-app/

为了说明我的用例,我更新了反应示例中思考

  • 应用程序
    • 可过滤产品表
      • 搜索栏
      • ProductTable(包含状态下的reflux存储)
        • 产品类别行
        • 产品行

正如预期的那样,在App既没有调用componentDidUpdate也没有调用componentWillUpdate

是否可以以理智的方式检测App组件中更新的子组件? 最好不修改子组件类?

我想避免将 props/state 移动到App

我想出了一个解决方案,它可以作为解决方案的下降(无需修改子组件,或了解整个应用程序状态,例如:Flux 模式):

App可以包装在一个组件中,该组件使用MutationObserver来跟踪 DOM 中的实际更改。

您可以在 App 中定义一个回调,该回调通过道具通过其子层次结构向下传递,如果调用子的 componentDidUpdate 方法,则触发该回调。 但是,如果您有很多孩子的深层层次结构,这可能会变得混乱。

我有一种情况,我想在单元测试中执行this.setProps(…) (当组件在没有父级的情况下呈现时)。 但是如果在有父母的情况下完成它会导致错误。

我的解决方法只是在单元测试中设置像<MyComponent renderingWithoutParentForTest={true} />这样的道具,并使用该道具作为条件。

不过,我承认这很丑陋。 在这种特殊情况下,这似乎是有道理的。

React 文档提出了两种处理子对父通信的方法。 已经提到了第一个,它是将一个或多个函数作为 props 从父组件通过层次结构向下传递,然后在子组件中调用它们。

孩子对父母的沟通: https : //facebook.github.io/react/tips/communicate-between-components.html

二是使用全局事件系统。 您可以构建自己的事件系统,该系统可以很容易地用于这些目的。 它可能看起来像这样:

var GlobalEventSystem = {

  events: {},

  subscribe: function(action, fn) {
    events[action] = fn;
  },

  trigger: function(action, args) {
    events[action].call(null, args);
  }
};

var ParentComponent = React.createClass({

  componentDidMount: function() {
    GlobalEventSystem.subscribe("childAction", functionToBeCalledWhenChildTriggers);
  },

  functionToBeCalledWhenChildTriggers: function() {
    // Do things
  }
)};

var DeeplyNestedChildComponent = React.createClass({

   actionThatHappensThatShouldTrigger: function() {
     GlobalEventSystem.trigger("childAction");
   }
});

这在某种程度上类似于 Flux 模式。 使用 Flux 架构可能有助于解决您的问题,因为订阅事件的视图组件的想法是 Flux 的重要组成部分。 所以你会让你的父组件订阅你 Store(s) 中的一些事件,这些事件本来是由子组件触发的。

如果你有更大的应用程序,事件系统是比传递道具更好的解决方案。

按照flux 的建议进行思考。 组件 -> 动作 -> 调度器 -> 存储

在商店里你会有你的状态。 您将注册要存储的组件回调。 您从任何组件和任何其他组件触发操作,即侦听商店的更改正在获取数据。 无论您如何更改层次结构,您始终可以在需要的地方获取数据。

调度员.js:

var Promise = require('es6-promise').Promise;
var assign = require('object-assign');

var _callbacks = [];
var _promises = [];

var Dispatcher = function () {
};

Dispatcher.prototype = assign({}, Dispatcher.prototype, {

    /**
     * Register a Store's callback so that it may be invoked by an action.
     * @param {function} callback The callback to be registered.
     * @return {number} The index of the callback within the _callbacks array.
     */

    register: function (callback) {
        _callbacks.push(callback);
        return _callbacks.length - 1;
    },

    /**
     * dispatch
     * @param  {object} payload The data from the action.
     */

    dispatch: function (payload) {
        var resolves = [];
        var rejects = [];
        _promises = _callbacks.map(function (_, i) {
            return new Promise(function (resolve, reject) {
                resolves[i] = resolve;
                rejects[i] = reject;
            });
        });

        _callbacks.forEach(function (callback, i) {
            Promise.resolve(callback(payload)).then(function () {
                resolves[i](payload);
            }, function () {
                rejects[i](new Error('#2gf243 Dispatcher callback unsuccessful'));
            });
        });
        _promises = [];
    }
});

module.exports = Dispatcher;

一些商店样本:

const AppDispatcher = require('./../dispatchers/AppDispatcher.js');
const EventEmitter = require('events').EventEmitter;
const AgentsConstants = require('./../constants/AgentsConstants.js');
const assign = require('object-assign');

const EVENT_SHOW_ADD_AGENT_FORM = 'EVENT_SHOW_ADD_AGENT_FORM';
const EVENT_SHOW_EDIT_AGENT_FORM = 'EVENT_SHOW_EDIT_AGENT_FORM';

const AgentsStore = assign({}, EventEmitter.prototype, {

    emitShowAgentsAddForm: function (data) {
        this.emit(EVENT_SHOW_ADD_AGENT_FORM, data);
    },
    addShowAgentsAddListener: function (cb) {
        this.on(EVENT_SHOW_ADD_AGENT_FORM, cb);
    },
    removeShowAgentsAddListener: function (cb) {
        this.removeListener(EVENT_SHOW_ADD_AGENT_FORM, cb);
    }

});

AppDispatcher.register(function (action) {

    switch (action.actionType) {
        case AgentsConstants.AGENTS_SHOW_FORM_EDIT:
            AgentsStore.emitShowAgentsEditForm(action.data);
            break;
        case AgentsConstants.AGENTS_SHOW_FORM_ADD:
            AgentsStore.emitShowAgentsAddForm(action.data);
            break;
    }
});


module.exports = AgentsStore;

动作文件:

var AppDispatcher = require('./../dispatchers/AppDispatcher.js');
var AgentsConstants = require('./../constants/AgentsConstants.js');

var AgentsActions = {

    show_add_agent_form: function (data) {
        AppDispatcher.dispatch({
            actionType: AgentsConstants.AGENTS_SHOW_FORM_ADD,
            data: data
        });
    },
    show_edit_agent_form: function (data) {
        AppDispatcher.dispatch({
            actionType: AgentsConstants.AGENTS_SHOW_FORM_EDIT,
            data: data
        });
    },
}

module.exports = AgentsActions;

在某些组件中,您就像:

...
    componentDidMount: function () {
        AgentsStore.addShowAgentsAddListener(this.handleChange);
    },
    componentWillUnmount: function () {
        AgentsStore.removeShowAgentsAddListener(this.handleChange);
    },
...

这段代码有点旧,但效果很好,你绝对可以了解它是如何工作的

你可以使用 React.Children.count 如果你只想知道孩子的数量何时改变,或者你可以访问每个孩子的 React.Children.map/forEach。

看这个例子(我在 useEffect 钩子中使用它,但你可以在 componentDidMount 或 DidUpdate 中使用它)

const BigBrother = props => {
   const { children } = props;
   const childrenIds = React.Children.map(children, child => {
      return child ? child.props.myId : null;
   }).filter(v => v !== null);
   useEffect(() => {
      // do something here
   }, [childrenIds.join("__")]);

  return (
    <div>
      <h2>I'm the big brother</h2>
      <div>{children}</div>
    </div>
}

然后你可以像这样使用它(使用动态列表!)

<BigBrother>
  <LilBrother myId="libindi" />
  <LilBrother myId="lisoko" />
  <LilBrother myId="likunza" />
</BigBrother>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM