错误:无法读取未定义的React Native属性'push'

时间:2015-09-21 13:30:15

标签: javascript ios this undefined react-native

我目前正在尝试根据此教程学习React Native:http://www.appcoda.com/react-native-introduction/

在复制大部分代码时(文本中的小改动)我收到了这个错误:

Error: Cannot read property 'push' of undefined

如果我尝试推送新的Navigator View,则会发生此错误。这是条纹下来的代码(最后的完整代码,但认为这里只有一个简短版本更具可读性):

<TouchableHighlight onPress={() => this._rowPressed(eve)} >



    _rowPressed(eve) {
  this.props.navigator.push({
    title: "Property",
    component: SingleEvent,
    passProps: {eve}
  });
}

也许有人可以解释为什么 this.props.navigator 未定义以及我如何使用它。我很抱歉这个基本问题,但我搜索了很多,但还没找到这个问题的答案。我尝试将.bind(this)添加到_rowPressed函数中,并将所有内容重写为NavigatorIOS视图但尚无效。

如果有人能向我解释,那会很好。

一切顺利 丹尼尔

完整错误报告:

Error: Cannot read property 'push' of undefined
 stack: 
  Dates._rowPressed                                      index.ios.bundle:52051
  Object._createClass.value.React.createElement.onPress  index.ios.bundle:52033
  React.createClass.touchableHandlePress                 index.ios.bundle:41620
  TouchableMixin._performSideEffectsForTransition        index.ios.bundle:39722
  TouchableMixin._receiveSignal                          index.ios.bundle:39640
  TouchableMixin.touchableHandleResponderRelease         index.ios.bundle:39443
  executeDispatch                                        index.ios.bundle:15431
  forEachEventDispatch                                   index.ios.bundle:15419
  Object.executeDispatchesInOrder                        index.ios.bundle:15440
  executeDispatchesAndRelease                            index.ios.bundle:14793
 URL: undefined
 line: undefined
 message: Cannot read property 'push' of undefined

通过TabBarIOS包含在主视图中的父视图代码:

    'use strict';

var React = require('react-native');
var singleEvent = require('./singleEvent');
var REQUEST_URL = 'http://***/dates/24-09-2015.json';



var {
    Image,
    StyleSheet,
    Text,
    View,
    Component,
    ListView,
    NavigatorIOS,
    TouchableHighlight,
    TabBarIOS,
    ActivityIndicatorIOS
} = React;


var styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
        padding: 10
    },
    thumbnail: {
        width: 53,
        height: 81,
        marginRight: 10
    },
    rightContainer: {
        flex: 1
    },
    title: {
        fontSize: 16,
        marginBottom: 8
    },
    author: {
        color: '#656565',
        fontSize: 12
    },
    separator: {
       height: 1,
       backgroundColor: '#dddddd'
   },
   listView: {
       backgroundColor: '#F5FCFF'
   },
   loading: {
       flex: 1,
       alignItems: 'center',
       justifyContent: 'center'
   }   
});

class Dates extends Component {

  constructor(props) {
      super(props);

      this.state = {
        isLoading: true,
        dataSource: new ListView.DataSource({
           rowHasChanged: (row1, row2) => row1 !== row2
        })
      };
    }


    componentDidMount() {
       this.fetchData();
    }

    fetchData() {
       fetch(REQUEST_URL)
       .then((response) => response.json())
       .then((responseData) => {
           this.setState({
               dataSource: this.state.dataSource.cloneWithRows(responseData),
               isLoading: false
           });
       })
       .done();
    }

      render() {
       if (this.state.isLoading) {
           return this.renderLoadingView();
       }

       return (
            <ListView
                dataSource={this.state.dataSource}
                renderRow={this.renderEvent.bind(this)}
                style={styles.listView}
                />
        );
      }  
    renderLoadingView() {
        return (
            <View style={styles.loading}>
                <ActivityIndicatorIOS size='large'/>
                <Text>Loading Events...</Text>
            </View>
        );
    }

    renderEvent(eve) {
       return (
            <TouchableHighlight onPress={() => this._rowPressed(eve).bind(this)}  underlayColor='#dddddd'>
                <View>
                    <View style={styles.container}>
                        <View style={styles.rightContainer}>
                            <Text style={styles.title}>{eve.value.name}</Text>
                            <Text style={styles.author}>{eve.value.location}</Text>
                        </View>
                    </View>
                    <View style={styles.separator} />
                </View>
            </TouchableHighlight>
       );
    }

    _rowPressed(eve) {

      console.log(eve, this.props);

      this.props.navigator.push({
        title: "Property",
        component: SingleEvent,
        passProps: {eve}
      });
    }
}
module.exports = Dates;

如果单击ListView,则应包含单个视图:

'use strict';

var React = require('react-native');

var {
  StyleSheet,
  Text,
  TextInput,
  View,
  TouchableHighlight,
  ActivityIndicatorIOS,
  Image,
  Component
} = React;

var styles = StyleSheet.create({
    description: {
        fontSize: 16,
        backgroundColor: 'white'
    },
    title : {
        fontSize : 22
    },
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    }
});

class SingleEvent extends Component {
    render() {
        var eve = this.props.eve;
        var description = (typeof eve.value.description !== 'undefined') ? eve.value.description : '';
        return (
            <View style={styles.container}>
                <Text style={styles.title}>{eve.value.name}</Text>
                <Text style={styles.description}>{description}</Text>
            </View>
        );
    }
}

module.exports = SingleEvent;

index.ios.js所有视图合并在一起:

'use strict';

var React       = require('react-native');
var Dates       = require('./Dates');
//var Eventlist       = require('./eventlist');
var NearYou     = require('./NearYou');

var icons         = [];
icons['place']    = require('image!ic_place_18pt');
icons['reorder']  = require('image!ic_reorder_18pt');
icons['grade']    = require('image!ic_grade_18pt');
icons['people']   = require('image!ic_group_18pt');

var {
    Image,
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ListView, 
    TouchableHighlight,
    TabBarIOS,
    Component
} = React;

class allNightClub extends Component {

    constructor(props) {
        super(props);
        this.state = {
            selectedTab: 'dates'
        };
    }

    render() {
        return (
            <TabBarIOS selectedTab={this.state.selectedTab}>
                <TabBarIOS.Item
                    selected={this.state.selectedTab === 'dates'}
                    icon={icons['reorder']}
                    title= 'Events'
                    onPress={() => {
                        this.setState({
                            selectedTab: 'dates'
                        });
                    }}>
                    <Dates navigator={navigator} />
                </TabBarIOS.Item>
               <TabBarIOS.Item
                    selected={this.state.selectedTab === 'nearyou'}
                    title= 'Favorites'
                    icon={icons['grade']}
                    onPress={() => {
                        this.setState({
                            selectedTab: 'nearyou'
                        });
                    }}>
                    <NearYou navigator={navigator} />
                </TabBarIOS.Item>
                <TabBarIOS.Item
                    selected={this.state.selectedTab === 'nearyou'}
                    title= 'Near You'
                    icon={icons['place']}
                    onPress={() => {
                        this.setState({
                            selectedTab: 'nearyou'
                        });
                    }}>
                    <NearYou navigator={navigator} />
                </TabBarIOS.Item> 
                <TabBarIOS.Item
                    selected={this.state.selectedTab === 'nearyou'}
                    title= 'People'
                    icon={icons['people']}
                    onPress={() => {
                        this.setState({
                            selectedTab: 'nearyou'
                        });
                    }}>
                    <NearYou navigator={navigator} />
                </TabBarIOS.Item> 
            </TabBarIOS>
        );
    }
}

AppRegistry.registerComponent('allNightClub', () => allNightClub);

3 个答案:

答案 0 :(得分:4)

你在index.ios.js中的

引用了这里没有设置的导航器。

<Dates navigator={navigator} />

所以,正如我所知,你必须选择使用NavigatorIOS:

<强> 1。 NavigatorIOS作为选项卡的子项

您需要将导航器定义为TabViewItems的子项,它本身会加载相应的视图:

var styles = StyleSheet.create({
    container: {
        flex: 1,
    }
});

<TabBarIOS.Item>
<NavigatorIOS
    style={styles.container}
    initialRoute={{
        title: 'Dates',
        component: Dates,
    }}
/>
</TabBarIOS.Item>

<强> 2。 NavigatorIOS作为根元素

class allNightClub extends Component {

  render() {
        return (
            <NavigatorIOS
                style={styles.container}
                initialRoute={{
                  title: 'Index',
                  component: Index
                }}
            />
        );
    }
}

这就是它对我有用的方式。我将index.ios.js的原始代码放入Index.js并进行了以下更改:

Index.js

<Dates
    navigator={this.props.navigator}
/>

Dates.js

<TouchableHighlight onPress={() => this._rowPressed(eve)}  underlayColor='#dddddd'>

答案 1 :(得分:1)

从我可以推断的情况来看,即使没有bind-statements,你对this.props.navigator的调用也应该有效。
我的第一个想法是:导航器项目是否从其父项传递给您的日期组件?

return (
  <Dates
    navigator={navigator}
    ... />

可能在渲染导航器的渲染器函数中...

您的输出与控制台声明有什么关系?

console.log(eve, this.props)

答案 2 :(得分:0)

我今天遇到了这个问题,原因是你需要调用屏幕,你可以使用带有NavigatorIOS组件的this.props.navigator.push。这将设置导航器道具。 E.g。

<NavigatorIOS
    style={styles.container}
    initialRoute={{
    title: '',
    component: DemoScreen
  }}
/>

现在,在您的DemoScreen中,您可以使用this.props.navigator