react-native:`this.state`在`render`中未定义

时间:2015-11-23 02:00:11

标签: javascript reactjs react-native

我有以下代码,导致this.stateundefined

articles.js

const React = require('react-native')
const _ = require('lodash')

const styles = require('../styles/articles')
const api = require('../data/api')

const {
  ListView,
  View,
  Text,
  Image
} = React

const Articles = React.createClass({

  getInitialState: () => {
    return { articles: [] }
  },

  componentDidMount: () => {
    const self = this
    const body = [{ screen_name: 'wired' }]
    api.get('timelines', body)
      .then(data => {
        self.setState({ articles : data })
      })
  },

  renderArticle: article => {
    const { container, thumbnail, rightContainer, title, year } = styles;

    return (
      <View key={article.id} style={container}>
        <Text style={title}>{article.title}</Text>
      </View>
    )
  },

  render: () => {
    console.log('render', this.state)
    const articles = _.map(this.state.articles, article => renderArticle(article), this)
    return <View style={styles.listView}>{articles}</View>
  }
})

module.exports = Articles

index.ios.js

const React = require('react-native')

const Articles = require('./src/components/articles')

React.AppRegistry.registerComponent('movies', () => Articles)
console.log方法中的

render表示this.state未定义。我做错了什么?

1 个答案:

答案 0 :(得分:12)

您正在使用带有箭头功能的React.createClass,这会混淆与this的绑定。

所以不要做

render () => {}

DO

render: function () {}

或切换到ES6类,这将使您当前的类看起来像这样

class Articles extends React.Component {
    renderArticles = () => {}
    render() {} // render and other lifecycle methods are always left without an arrow function
}

在ES6中,React不再支持.createClass为您提供的自动绑定功能,这就是您在编写ES6 React组件时使用和箭头功能或使用.bind的原因。

另请注意,当使用Babel,ES6和React时,某些功能可能隐藏在舞台标志后面,您必须在进行时对其进行调查!