2016-04-22 97 views
2

我正在開發react-redux應用程序,並且出於某種原因我調用的操作沒有到達reducer(其中我目前只有一條日誌語句)。我已附上我認爲相關的代碼,任何貢獻將不勝感激。在React + Redux中,操作不會觸發Reducer

操作在組分函數內部調用:

onSearchPressed() { 
    console.log('search pressed'); 
    this.props.addToSaved(); 
} 

動作/ index.js:

var actions = exports = module.exports 

exports.ADD_SAVED = "ADD_SAVED"; 

exports.addToSaved = function addToSaved() { 
    console.log('got to ADD_SAVED step 2'); 
    return { 
    type: actions.ADD_SAVED 
    } 
} 

減速器/ items.js:

const { 
    ADD_SAVED 
} = require('../actions/index') 

const initialState = { 
    savedList: [] 
} 

module.exports = function items(state = initialState, action) { 
    let list 

    switch (action.type) { 
     case ADD_SAVED: 
      console.log('GOT to Step 3'); 
      return state; 
     default: 
      console.log('got to default'); 
      return state; 
    } 
} 

減速器/ index.js:

const { combineReducers } = require('redux') 
const items = require('./items') 

const rootReducer = combineReducers({ 
    items: items 
}) 

module.exports = rootReducer 

店/配置-store.js:

import { createStore } from 'redux' 
import rootReducer from '../reducers' 

let store = createStore(rootReducer) 

編輯:爲onSearchPressed整個組件:

class MainView extends Component { 
    onSearchPressed() { 
     this.props.addToSaved(); 
    } 
    render() { 
     console.log('MainView clicked'); 
     var property = this.props.property; 

     return (
      <View style={styles.container}> 
       <Image style={styles.image} 
        source={{uri: property.img_url}} /> 
       <Text style={styles.description}>{property.summary}</Text> 
       <TouchableHighlight style = {styles.button} 
         onPress={this.onSearchPressed.bind(this)} 
         underlayColor='#99d9f4'> 
         <Text style = {styles.buttonText}>Save</Text> 
        </TouchableHighlight> 
      </View> 
     ); 
    } 
} 

module.exports = MainView; 
+0

檢查的console.log上onSearchPressed(this.props)(),並確保它不爲空 – QoP

+0

@QoP的console.log(this.props)正確填充。 – user3802348

+0

這很奇怪!嘗試改變exports.addToSaved =功能addToSaved(){}以exports.addToSaved =函數(){} – QoP

回答

2

正如裏克·喬利在你的問題中提到的意見,你的onSearchPressed()功能實際上並不調度該動作,因爲addToSaved()只是返回一個動作對象 - 它不派遣任何東西。

如果你想從一個組件調度操作,您應該使用react-redux你的份(S)連接到終極版。例如:

const { connect } = require('react-redux') 

class MainView extends Component { 
    onSearchPressed() { 
    this.props.dispatchAddToSaved(); 
    } 
    render() {...} 
} 

const mapDispatchToProps = (dispatch) => { 
    return { 
    dispatchAddToSaved:() => dispatch(addToSaved()) 
    } 
} 

module.exports = connect(null, mapDispatchToProps)(MainView) 

查看'Usage With React' section of the Redux docs瞭解更多信息。

相關問題