简体   繁体   English

Action不会在React + Redux中触发reducer

[英]Action does not trigger a reducer in React + Redux

I'm working on a react-redux app and for some reason the action I call does not reach the reducer (in which I currently only have a log statement). 我正在研究react-redux应用程序,由于某种原因,我调用的动作没有到达reducer(我目前只有一个日志语句)。 I have attached the code I feel is relevant and any contributions would be highly appreciated. 我附上了我认为相关的代码,我们将非常感谢任何贡献。

Action called within function in component: 在组件中的函数内调用的操作:

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

actions/index.js: 动作/ 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: 减速器/ 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: 减速器/ index.js:

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

const rootReducer = combineReducers({
  items: items
})

module.exports = rootReducer

store/configure-store.js: 存储/配置 - store.js:

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

let store = createStore(rootReducer)

EDIT: Entire component for onSearchPressed: 编辑: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;

As Rick Jolly mentioned in the comments on your question, your onSearchPressed() function isn't actually dispatching that action, because addToSaved() simply returns an action object - it doesn't dispatch anything. 正如Rick Jolly在你的问题的评论中提到的那样,你的onSearchPressed()函数实际上并没有调度那个动作,因为addToSaved()只是返回一个动作对象 - 它不会发送任何东西。

If you want to dispatch actions from a component, you should use react-redux to connect your component(s) to redux. 如果要从组件调度操作,则应使用react-redux将组件连接到redux。 For example: 例如:

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. 有关详细信息,请参阅Redux文档“使用React”部分

Recently I faced issue like this and found that I had used action import but it has to come from props. 最近我遇到这样的问题,发现我使用了动作导入,但它必须来自道具。 Check out all uses of toggleAddContactModal. 查看toggleAddContactModal的所有用法。 In my case I had missed toggleAddContactModal from destructuring statement which caused this issue. 在我的情况下,我错过了来自解构声明的toggleAddContactModal导致了这个问题。

import React from 'react'
import ReactDOM from 'react-dom'
import Modal from 'react-modal'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import {
  fetchContacts,
  addContact,
  toggleAddContactModal
} from '../../modules/contacts'
import ContactList from "../../components/contactList";

Modal.setAppElement('#root')

class Contacts extends React.Component {
  componentDidMount(){
    this.props.fetchContacts();
  }
  render(){
    const {fetchContacts, isFetching, contacts, 
      error, isAdding, addContact, isRegisterModalOpen,
      toggleAddContactModal} = this.props;
    let firstName;
    let lastName;
    const handleAddContact = (e) => {
      e.preventDefault();
      if (!firstName.value.trim() || !lastName.value.trim()) {
        return
      }
      addContact({ firstName : firstName.value, lastName: lastName.value});
    };

    return (
      <div>
        <h1>Contacts</h1>
        <div>
          <button onClick={fetchContacts} disabled={isFetching}>
            Get contacts
          </button>
          <button onClick={toggleAddContactModal}>
            Add contact
          </button>
        </div>
        <Modal isOpen={isRegisterModalOpen} onRequestClose={toggleAddContactModal}>
          <input type="text" name="firstName" placeholder="First name" ref={node =>         
 (firstName = node)} ></input>
      <input type="text" name="lastName" placeholder="Last name" ref={node => 
(lastName = node)} ></input>
          <button onClick={handleAddContact} disabled={isAdding}>
            Save
          </button>
        </Modal>
        <p>{error}</p>
        <p>Total {contacts.length} contacts</p>
        <div>
          <ContactList contacts={contacts} />
        </div>
      </div>
    );
  }
}
const mapStateToProps = ({ contactInfo }) => {
  console.log(contactInfo)
  return ({
    isAdding: contactInfo.isAdding,
    error: contactInfo.error,
    contacts: contactInfo.contacts,
    isFetching: contactInfo.isFetching,
    isRegisterModalOpen: contactInfo.isRegisterModalOpen
  });
}

const mapDispatchToProps = dispatch =>
  bindActionCreators(
    {
      fetchContacts,
      addContact,
      toggleAddContactModal
    },
    dispatch
  )

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Contacts)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM