【问题标题】:react-native: `this.state` is undefined in `render`react-native: `this.state` 在`render` 中未定义
【发布时间】:2015-11-23 02:00:10
【问题描述】:

我有以下代码,导致this.state 成为undefined

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)

render 方法中的console.log 表示this.state 未定义。我做错了什么?

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    您正在使用带有箭头函数的React.createClass,这会破坏与this 的绑定。

    所以不要这样做

    render () => {}
    

    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 时,某些功能可能隐藏在阶段标志后面,您必须在进行过程中进行调查!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-08
      • 2019-05-29
      • 2018-01-24
      相关资源
      最近更新 更多