Response-native: `this.state` undefined in` render`

I have the following code that leads to 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) 

console.log in the render method says this.state is undefined. What am I doing wrong?

+5
source share
1 answer

You are using React.createClass with arrow functions, this will ruin the binding to this .

So, instead of doing

 render () => {} 

make

 render: function () {} 

or switch to ES6 classes that will make your current class look like

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

In ES6, React no longer supports the auto-link feature provided by .createClass , for which you want to use either the arrow function or use .bind when writing ES6 React components.

Also note that when using Babel, ES6 and React, some functions may be hidden behind stage flags, you will have to examine them as you move!

+12
source

Source: https://habr.com/ru/post/1236578/


All Articles