2016-04-20 26 views
0

我目前正在構建一個react-redux應用程序,當我點擊「保存」按鈕時,應用程序應該在actions/index.js中調用函數addToSaved。但是,我收到'this.props.addToSaved未定義'錯誤,而不是函數。我在actions/index.js中定義了函數,但是想知道我是否缺少其他東西。這是我目前正在做的:this.props.function()在React應用程序中未定義?

在組件/ MainView.js

'use strict'; 
import { addToSaved } from "../actions" 

var React = require('react-native'); 
var { 
    StyleSheet, 
    Image, 
    View, 
    Text, 
    Component, 
    TouchableHighlight 
} = React; 


class MainView extends Component { 
    onSearchPressed() { 
     console.log('search pressed'); 
     this.props.addToSaved(); 
    } 
    render() { 
     return (
      <View style={styles.container}> 
       <Image style={styles.image} 
        source={{uri: pic.img_url}} /> 
       <TouchableHighlight style = {styles.button} 
         onPress={this.onSearchPressed.bind(this)} 
         underlayColor='#99d9f4'> 
         <Text style = {styles.buttonText}>Save</Text> 
       </TouchableHighlight> 
      </View> 
     ); 
    } 
} 

module.exports = MainView; 
在行動/ index.js

var actions = exports = module.exports 
exports.ADD_SAVED = 'ADD_SAVED' 
exports.addToSaved = function addToSaved() { 
    console.log('got to ADD_SAVED'); 

}

回答

3

你要導入addToSaved,並期待它出現在this.props

如果你希望它是在this.props訪問,你需要傳遞到組件實例

<MainView addToSaved={addToSaved} /> 
+0

看來問題,也宣告道具組件時,請確保您已經添加道具驗證HTTP ://facebook.github.io/react/docs/reusable-components.html#default-prop-values –

+0

@bchemy所以我仍然應該導入addToSaved,但也將該行添加到MainView類? – user3802348

+1

您不需要將'addToSaved'導入到'MainView.js'中,但是您確實需要將其導入到任何文件中實例化一個'MainView'(即通過'')並添加該行。 – bcherny

相關問題