首页 > 解决方案 > 为什么我的 redux 应用程序中的 state 总是为 null?

问题描述

我正在构建一个非常简单的联系人应用程序来熟悉 React 和 Redux。现在我正在尝试构建添加联系人的功能。我以为我正确设置了动作和减速器,但目前传递给减速器的状态为空。我希望当前的联系人列表处于通过的状态。如果我在减速器执行后记录状态,它甚至没有得到我希望添加的一个联系人,它仍然是空的。任何帮助表示赞赏!

我的代码如下

行动:

function addContact(contact) {
  console.log("it gets to the action");
  return {
    type: 'ADD_CONTACT',
    payload: contact
  }
}

export default addContact;

AddContacts 减速器:

export default function (state = {}, action) {
  console.log(state);

  switch (action.type) {
    case 'ADD_CONTACT':
      return Object.assign({}, state, {
        contacts: [
          ...state.contacts,
          {
            name: action.payload.name,
            phone: action.payload.phone
          }
        ]
      })
  }
  return state;
}

调用此操作的组件:

import React, { Component } from 'react'
import AddContactButton from './AddContactButton';
import { connect } from 'react-redux'
import addContact from '../actions/action_add_contact'
import { bindActionCreators } from 'redux'

class AddContactModal extends Component {

  constructor() {
    super();
    this.state = {firstName: "", phone: ""};
  }

  handleNameChange(event) {
    this.setState({firstName: event.target.value})
  }

  handlePhoneChange(event) {
    this.setState({phone: event.target.value});
  }

  onClick() {
    console.log($r.store.getState());
    this.props.addContact({"name": this.state.firstName, "phone": this.state.phone});
  }

  render() {

    return(
      <div>
        <input type="text" className="name" placeholder="Contact Name" onChange={(event) => this.handleNameChange(event)}/>
        <input type="text" className="phone" placeholder="Contact Phone" onChange={(event) => this.handlePhoneChange(event)}/>
        <AddContactButton firstName={this.state.firstName} firstName={this.state.phone} onClick={() => this.onClick()}/>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    contacts: state.contacts
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addContact: addContact }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(AddContactModal)

店铺创建:

const createStoreWithMiddleware = applyMiddleware()(createStore);
const initialState = {
  "contacts": [
    {
      "name": "Miguel Camilo",
      "phone": "123456789"
    },
    {
      "name": "Peter",
      "phone": "883292300348"
    },
    {
      "name": "Jessica",
      "phone": "8743847638473"
    },
    {
      "name": "Michael",
      "phone": "0988765553"
    }
  ],
  "activeContact": null
};

ReactDOM.render(
  <Provider store={ createStoreWithMiddleware(reducers, initialState) }>
   <App />
  </Provider>
, document.querySelector('.container'));

Contacts reducer 只返回一个硬编码的联系人列表来设置初始状态:

export default function () {
  return [{
    "name": "Miguel Camilo",
    "phone": "123456789"
  },{
    "name": "Peter",
    "phone": "883292300348"
  },{
    "name": "Jessica",
    "phone": "8743847638473"
  },{
    "name": "Michael",
    "phone": "0988765553"
  }];
}

我很确定我的问题来自我在组件中使用 mapStateToProps 和 mapDispatchToProps,当我查看 redux 状态时,我看到它添加了一个我认为我不想要的集合“addContacts”?它不应该只是从操作中获取有效负载并将其添加到“联系人”集合吗?

标签: javascriptreactjsreduxreact-reduxstate

解决方案


我假设你错过了调度:

    function addContact(contact) {
        console.log("it gets to the action");
        dispatch({
           type: 'ADD_CONTACT',
           payload: contact
        });
   }

   export default addContact;

推荐阅读