【问题标题】:React: cannot access mixin function inside getDefaultPropsReact:无法访问 getDefaultProps 中的 mixin 函数
【发布时间】:2015-08-05 02:56:22
【问题描述】:

我正在尝试从 getDefaultProps 访问 mixin 中定义的函数,但我得到了 undefined is not a function。基本上我正在使用react-intl 并且我的列的默认标签应该被翻译。为什么我无法从 getDefaultProps 中访问 mixin 中定义的函数?

var React = require('react');
var ReactIntl = require('react-intl');
var IntlMixin = ReactIntl.IntlMixin;

var Index = React.createClass({

  mixins: [IntlMixin],

  getDefaultProps: function () {
    return ({
      options: {
        attributes: [{name: 'name', label: this.getIntlMessage('Index.name'), index: 0}],
        view: "tiles"
      }
    });
  },

  render: function() {
    return <div>{this.props.options.attributes[0].label}</div>
  }
});

module.exports = Index;

【问题讨论】:

    标签: javascript node.js reactjs mixins


    【解决方案1】:

    无法访问它,因为getDefaultProps 只被调用一次,而不是在您正在创建的类的实例的上下文中。 this 上下文不正确。

    您需要将检索转移到实例函数中,例如render

    您还应该知道,在getDefaultProps 中返回的数组或对象实例在所有实例之间共享。我不知道您是如何使用它的,但根据您使用这些值的方式,它可能会导致问题。

    【讨论】:

    • 感谢您的回答,我理解您的观点,但我觉得能够从 getDefaultProps 访问上下文会很好。也许我对 React 的理解不够好。 :)
    • 不知道为什么不赞成,这个答案是正确的,你不能从getDefaultProps 访问实例上下文,因为没有实例。根据文档:“在创建类时调用一次并缓存”
    • @AlanSouza - 你无法访问它......它不存在,因为没有类。您需要以不同的方式使用该功能,而不是依赖 mixin 方法。
    • 这对 createClass 来说很奇怪。在带有普通 JS 类的 0.13 中,它是构造函数的属性,而不是原型,称为 defaultProps(连同 getInitialState 被删除并在构造函数中手动设置 this.state)。
    • @FakeRainBrigand- 尽管最终,在这两种情况下,它仍然表现为类的静态和非实例方法/值。所以,他们确实保持了一致。
    猜你喜欢
    • 2018-11-27
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2017-05-06
    • 2017-02-27
    • 1970-01-01
    相关资源
    最近更新 更多