刷新页面后,useEffect运行api请求

时间:2020-05-01 21:04:01

标签: javascript reactjs react-hooks

我的组件应提取帐户有问题。 我有一个useEffect钩子来运行请求,但仅在刷新时才运行。 useEffect钩子运行我的console.log,但是直到我手动刷新后才启动api请求。 该应用程序的一般流程是,一旦您登录,然后启动请求以显示您的帐户表。

组件:

import React, { useEffect } from 'react';
import { func, object } from 'prop-types';
import { connect } from "react-redux";
import { getAllPlaidAccountsById } from "../../actions/accountActions";
import styles from "./DebtTable.css";


const DebtTable = ({ auth: { user },  getAllPlaidAccountsById, account: accounts }) => {
  useEffect(() => {
   getAllPlaidAccountsById(user._id);
  }, [getAllPlaidAccountsById]);

  if (accounts && accounts !== null) {
    return (
      <table className={styles.accountsTable}>
        <thead>
        <tr>
          <th>Account Name</th>
          <th>Account Type</th>
          <th>Interest Rate</th>
          <th>Min Payment</th>
          <th>Limit</th>
          <th>Balance</th>
          <th>Due Date</th>
        </tr>
        </thead>
        <tbody>
        {
          accounts.accounts.map((account) => {
            return account.map((acct, idx) => {
              const leftBottomCell = idx === accounts.length - 1 ? 'leftBottomCell' : '';
              const rightBottomCell = idx === accounts.length - 1 ? 'rightBottomCell' : '';

              return (
                <tr key={account.accountId}>
                  <td className={`${styles.accountName} ${styles[leftBottomCell]}`}>{acct.name}</td>
                  <td className={styles.accountType}>{acct.type}</td>
                  <td className={styles.interestRate}>-</td>
                  <td className={styles.minPayment}>-</td>
                  <td className={styles.accountLimit}>{`$${acct.balances.limit}`}</td>
                  <td className={styles.accountBalance}>{`$${acct.balances.current}`}</td>
                  <td className={`${styles.dueDate} ${styles[rightBottomCell]}`}>-</td>
                </tr>
              )
            })
          })
        }
        </tbody>
      </table>
    )
  }
  return null;
}
DebtTable.propTypes = {
  getAllPlaidAccountsById: func.isRequired,
  profile: object.isRequired,
  auth: object.isRequired
};

const mapStateToProps = (state) => ({
  profile: state.profile,
  account: state.account
});

export default connect(mapStateToProps, { getAllPlaidAccountsById })(DebtTable);

Redux动作:

import axios from "axios";
import {
  GET_ALL_PLAID_ACCOUNTS,
  GET_ALL_PLAID_ACCOUNTS_ERROR
} from "./types";

export const getAllPlaidAccountsById = (userId) => async dispatch => {
  try {
    const res = await axios.get(`/api/accounts/${userId}`);

    let creditCards = [];
    res.data.map(account => {
      if(account.type === 'credit') creditCards.push(account);
      return null;
    });

    dispatch({
      type: GET_ALL_PLAID_ACCOUNTS,
      payload: creditCards
    });

  } catch (err) {
    dispatch({
      type: GET_ALL_PLAID_ACCOUNTS_ERROR,
      payload: { msg: err }
    });
  }
};

Redux Reducer:

import {
  GET_ALL_PLAID_ACCOUNTS,
  GET_ALL_PLAID_ACCOUNTS_ERROR
} from '../actions/types';

const initialState = {
  account: null,
  accounts: [],
  error: {}
};

export default function(state = initialState, action) {
  const { type, payload } = action;

  switch (type) {
    case GET_ALL_PLAID_ACCOUNTS:
      return {
        ...state,
        accounts: [payload, ...state.accounts],
        loading: false
      };
    case GET_ALL_PLAID_ACCOUNTS_ERROR:
      return {
        ...state,
        error: payload,
        loading: false
      };
    default:
      return state;
  }
}

1 个答案:

答案 0 :(得分:2)

useEffect的第二个参数是控制useEffect何时执行的变量数组。当数组中变量的值更改时,useEffect将重新运行。参见https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

似乎user._id发生更改时您都希望获得帐户,因此您应该将包含该变量的数组作为useEffect的第二个参数传递。

useEffect(() => {
  getAllPlaidAccountsById(user._id);
}, [user._id]);