【问题标题】:Functions breaking in react native tutorialreact native教程中的功能中断
【发布时间】:2016-01-17 17:50:38
【问题描述】:

我正在尝试 React Native,而 getInitialState 和 componentDidMount 等 React 组件的功能正在中断。例如,我试过:

getInitialState: function() {
    return {
      movies: null,
    };
  },

哪个坏了。

当我把 es6 等价的时候,也就是:

constructor(props) {
    super(props);
    this.state = {
      movies: null,
    };
}

程序运行良好。 解决这个问题的最佳方法是什么,以便我能够使用教程中提到的 React 函数而不是将它们翻译成 es6?

谢谢!

【问题讨论】:

  • 这取决于你的组件是如何创建的。它是使用 createClass 还是 class extends 创建的?

标签: javascript reactjs react-native


【解决方案1】:

我看不到您的代码以了解您的组件是如何创建的,但我想我知道这里发生了什么。

如果您将组件设置为类:

class MyComponent extends React.Component {

}

你只能使用构造函数来设置你的初始状态:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      movies: null,
    };
  }

  render() {
    return <View />
  }
}

如果你使用 React.createClass 设置你的组件,你只能使用 getInitialState 设置你的初始状态:

var MyComponent = React.createClass({
  getInitalState: function() {
    return {
      movies: null,
    }
  },
  render: function() {
    return <View />
  }
})

所有其他生命周期方法都应该以相同的方式工作。请注意,如果您正在使用类,则在类中的每个函数之后放置一个逗号会破坏您的应用程序。

例如,这将中断:

class MyComponent extends React.Component {
  componentDidMount() {
    console.log("mounted")
  }, // <- No comma necessary
  render() {
    return <View />
  }
}

这行得通:

class MyComponent extends React.Component {
  componentDidMount() {
    console.log("mounted")
  }
  render() {
    return <View />
  }
}

使用 React.createClass 时的情况正好相反。您需要用逗号分隔函数:

这会中断:

var MyComponent = React.createClass({
  componentDidMount: function() {
     console.log("mounted")
  } // <- Needs a comma here.
  render: function() {
    return <View />
  }
})

这行得通:

var MyComponent = React.createClass({
  componentDidMount: function() {
     console.log("mounted")
  },
  render: function() {
    return <View />
  }
})

【讨论】:

  • 谢谢!对不起,我没有包括我如何设置我的组件。但这是正确的。
猜你喜欢
  • 2020-05-30
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 2016-11-08
  • 1970-01-01
  • 2020-04-08
  • 2018-08-18
  • 1970-01-01
相关资源
最近更新 更多