我有以下代码,导致 this.state
为 undefined
:
文章.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
未定义。我做错了什么?
最佳答案
您正在使用带有箭头函数的 React.createClass
,这会打乱与 this
的绑定(bind)。
所以而不是做
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
为您提供的自动绑定(bind)功能,这就是为什么您要使用箭头函数或使用 .bind
的原因编写 ES6 React 组件。
另请注意,在使用 Babel、ES6 和 React 时,某些功能可能隐藏在阶段标志后面,您必须在进行过程中调查这些!
关于javascript - native react : `this.state` 在 `render` 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33862677/