动作不会在React + Redux中触发reducer

我正在使用react-

redux应用程序,由于某种原因,我调用的操作未到达reducer(在该操作中,我目前只有一条log语句)。我已附上我认为相关的代码,我们将不胜感激。

在组件中的函数内调用的操作:

onSearchPressed() {

console.log('search pressed');

this.props.addToSaved();

}

actions / 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

}

}

reducers / 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;

}

}

reducers / index.js:

const { combineReducers } = require('redux')

const items = require('./items')

const rootReducer = combineReducers({

items: items

})

module.exports = rootReducer

store / configure-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;

回答:

正如Rick

Jolly在对问题的评论中提到的那样,您的onSearchPressed()函数实际上并未在分派该动作,因为addToSaved()仅返回一个动作对象-

它不会分派任何东西。

如果要从组件分派操作,则应使用react-redux将组件连接到redux。例如:

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)

See the ‘Usage With React’ section of the Redux

docs for more

information.

以上是 动作不会在React + Redux中触发reducer 的全部内容, 来源链接: utcz.com/qa/397355.html

回到顶部