减速器未更新组件状态

时间:2020-04-08 23:32:37

标签: node.js reactjs redux

我一直在努力使它整天工作,但是无法从文档或其他帖子中找到解决方案,因此希望有人能够为我提供帮助。

我有一个组件transactions,我从另一个组件dashboard.中调用了该组件,当transaction加载时,它触发一个动作,然后触发减速器。我确认减速器具有我正在寻找的有效负载,但由于某种原因,它不会导致componentWillUpdatecomponentWillReceivePropstransactions组件中执行。确实会导致componentWillUpdate中的componentWillReceivePropsdashboard运行,但是当我检查道具时,数据不存在。我添加了一些可能有用的代码,但是没有人知道为什么我的reducer没有触发transactions组件中的任何生命周期更新方法吗?感谢您的帮助!

=> Transactions.js

import React, { Component } from "react";
import PropTypes from "prop-types";

import { connect } from "react-redux";
import {
  getTransactionsFromMongo
} from "../../actions/transactionAction";

class Transactions extends Component {
  constructor(props) {
    super(props);
    this.state = {
      transactions: []
    };
  }
  componentDidMount() {
    console.log(this.props);
    this.props.getTransactionsFromMongo();
  }

  render() {
    return <p>Hello world</p>;
  }
}

Transactions.propTypes = {
  getTransactionsFromMongo: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  transactions: state.transactions
});

export default connect(
  mapStateToProps,
  { getTransactionsFromMongo }
)(Transactions);

=> transactionReducer.js

import { GET_MONGO_TRANSACTIONS, UPDATE_TRANSACTION } from "../actions/types";

const initialState = {
  transactions: "",
};

export default function(state = initialState, action) {
  switch (action.type) {
    case GET_MONGO_TRANSACTIONS:
      console.log("in get reducer");
      var tmp = JSON.stringify(action.payload);
      console.log(typeof(tmp));
      return {
        ...state,
        transactions: tmp
      };
    default:
      return state;
  }
}

=> Dashboard.js

import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { getAccounts, addAccount } from "../../actions/accountActions";

import Accounts from "./Accounts";
import Transactions from "./Transactions";

class Dashboard extends Component {
  componentDidMount() {
    this.props.getAccounts();
  }


  render() {

    dashboardContent = (<Transactions>Hello</Transactions>);

    return <div className="container">{dashboardContent}</div>;
  }
}

Dashboard.propTypes = {
  logoutUser: PropTypes.func.isRequired,
  getAccounts: PropTypes.func.isRequired,
  addAccount: PropTypes.func.isRequired,

};

const mapStateToProps = state => ({
  auth: state.auth,
  transactions: state.transactions
});

export default connect(
  mapStateToProps,
  { logoutUser, getAccounts, addAccount }
)(Dashboard);

0 个答案:

没有答案