为什么 axios 在我的程序中被调用两次

IT技术 javascript reactjs axios
2021-05-19 15:25:08

我正在尝试通过 redux 设置配置文件状态。但是由于某种原因,我的 axios 被调用了两次

我的数据库 profile.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create Schema
const ProfileSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "users"
  },
  preference: [
    {
      type: String
    }
  ],

  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = Profile = mongoose.model("profile", ProfileSchema);

myCreatePreferences 类

import React, { Component } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import checkboxes from "./checkboxes";
import Checkbox from "./Checkbox";
import axios from "axios";
import { Redirect } from "react-router";
import { withRouter } from "react-router-dom";
import Select from "react-select";
import { getCurrentProfile } from "../../actions/profileActions";
const options = [
  { value: "Guns", label: "Guns" },
  { value: "Gay Marriage", label: "Gay Marriage" },
  { value: "Abortion", label: "Abortion" },
  { value: "IT", label: "IT" }
];

class CreatePreferences extends Component {
  constructor() {
    super();
    this.state = {
      selectedOption: [],
      fireRedirect: false
    };
    this.onSubmit = this.onSubmit.bind(this);
  }
  onSubmit(e) {
    e.preventDefault();
    let tempArray = [];

    for (let i = 0; i < this.state.selectedOption.length; i++) {
      tempArray[i] = this.state.selectedOption[i].value;
    }
    const preference = {
      tempArray
    };
    //axios
    // .post("/api/profile/", { tempArray: tempArray })
    //.then(res => res.data)
    // .catch(err => console.log(err));
    this.props.getCurrentProfile(preference);
    this.setState({ fireRedirect: true });
  }

  handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };

  render() {
    const { selectedOption } = this.state;
    console.log(selectedOption.value);
    const { fireRedirect } = this.state;
    return (
      <div>
        <form onSubmit={this.onSubmit}>
          <Select
            value={selectedOption}
            isMulti
            onChange={this.handleChange}
            options={options}
          />
          <input
            type="submit"
            className="btn btn-info btn-block mt-4"
            value="Save Preferences"
          />
          {fireRedirect && <Redirect to={"/"} />}
        </form>
      </div>
    );
  }
}
CreatePreferences.propTypes = {
  profile: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
  profile: state.profile
});

export default connect(
  mapStateToProps,
  { getCurrentProfile }
)(withRouter(CreatePreferences));

我的个人资料Actionsclass

import axios from "axios";

import {
  GET_PROFILE,
  PROFILE_LOADING,
  GET_ERRORS,
  CLEAR_CURRENT_PROFILE
} from "./types";

//Get current profile

export const getCurrentProfile = preference => dispatch => {
  dispatch(setProfileLoading());
  axios
    .post("/api/profile", preference)
    .then(res =>
      dispatch({
        type: GET_PROFILE,
        payload: res.data
      })
    )
    .catch(err =>
      dispatch({
        type: GET_PROFILE,
        payload: { err }
      })
    );
};

//Profile Loading

export const setProfileLoading = () => {
  return {
    type: PROFILE_LOADING
  };
};
//Clear Profile
export const clearCurrentProfile = () => {
  return {
    type: CLEAR_CURRENT_PROFILE
  };
};

profileReducer.js

import {
  GET_PROFILE,
  PROFILE_LOADING,
  CLEAR_CURRENT_PROFILE
} from "../actions/types";

const initialState = {
  profile: null,
  profiles: null,
  loading: false
};

export default function(state = initialState, action) {
  switch (action.type) {
    case PROFILE_LOADING:
      return {
        ...state,
        loading: true
      };
    case GET_PROFILE:
      return {
        ...state,
        profile: action.payload,
        loading: false
      };
    case CLEAR_CURRENT_PROFILE:
      return {
        ...state,
        profile: null
      };
    default:
      return state;
  }
}

index.js 类 redux 存储。

import { combineReducers } from "redux";
import authReducer from "./authReducer";
import errorReducer from "./errorReducer";
import profileReducer from "./profileReducer";
import postReducer from "./postReducer";
export default combineReducers({
  auth: authReducer,
  errors: errorReducer,
  profile: profileReducer,
  post: postReducer
});

当我通过 axios 通过 profileActions 从 createPreference 类发布数据时,我收到了两个 axios 发布请求。它首先按预期填充首选项,但是它会立即进行另一个调用,并且首选项再次设置为空。 console.log(of the call)

preference: Array(2), _id: "5bbc73011f67820748fcd9ab", user: "5bb87db33cb39a844f0ea46a", date: "2018-10-09T09:21:05.968Z", __v: 0}
Dashboard.js:20 {preference: null, _id: "5bbc73011f67820748fcd9ab", user: "5bb87db33cb39a844f0ea46a", date: "2018-10-09T09:21:05.968Z", __v: 0}

对于如何解决这个问题,有任何的建议吗?

1个回答

由于我无法访问您的所有代码(并且无法调试它),因此这里有一个更好的方法来获取数据。我已经根据您所拥有的情况对其进行了结构化,如果您按照工作示例进行操作,您应该能够消除问题。

我做了什么:

  1. 重命名onSubmit={this.onSubmit}为更标准的声明this.handleSubmit方法
  2. this.setState()handleSubmit类方法中调用以移除selectedOption值,然后在 setState 回调中调用getCurrentProfile(value, history)value用您的替换tempArray
  3. 将您的更改<input type="submit" ... /><button type="submit" ... />
  4. returnaxios.get(...)通话添加了一个(我还包含了一个可能更容易理解async/await版本getCurrentProfile——也可以用axios.get通话代替您的axios.post通话)
  5. 删除Redirect并改为在action创建者内部放置重定向history.push('/');(一旦请求成功发送,它会将用户重定向回“/”——如果错误,则不重定向)
  6. 始终保持您的 redux 状态为 1:1。换句话说,如果它是一个数组,那么它仍然是一个数组(not null),如果它是一个字符串,它仍然是一个字符串(not number)......等等。PropTypes,如果您不保持这种 1:1 模式,则在使用您的应用程序时会抛出错误。例如,您最初将 设置为profile: null,但随后将其设置为profile: [ Object, Object, Object ... ]相反,它最初应该是:profile: []
  7. 使用 时PropTypes,请避免含糊不清的类型,例如objector array,而是描述它们的结构方式。
  8. 由于 redux 的性质以及您如何设置组件,您不需要 dispatch setProfileLoading您只需更新数据,连接的 React 组件就会更新以反映新的更改。在短时间内分别调度两个 redux 操作很可能会导致组件闪烁(将其视为this.setState()在一秒内彼此调用两次——它会导致您的组件闪烁)。

工作示例:https : //codesandbox.io/s/ovjq7k7516

选择选项.js

import React, { Component } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { withRouter } from "react-router-dom";
import Select from "react-select";
import { clearCurrentProfile, getCurrentProfile } from "../actions";

const options = [
  { value: "todos?userId=1", label: "Todos" },
  { value: "comments?postId=1", label: "Comments" },
  { value: "users?id=1", label: "Users" },
  { value: "albums?userId=1", label: "Albums" }
];

class SelectOption extends Component {
  state = {
    selectedOption: []
  };

  handleSubmit = e => {
    e.preventDefault();
    const { getCurrentProfile, history } = this.props;
    const { value } = this.state.selectedOption;

    this.setState({ selectedOption: [] }, () =>
      getCurrentProfile(value, history)
    );
  };

  handleChange = selectedOption => this.setState({ selectedOption });

  render = () => (
    <div className="container">
      <form onSubmit={this.handleSubmit}>
        <Select
          value={this.state.selectedOption}
          onChange={this.handleChange}
          options={options}
        />
        <div className="save-button">
          <button type="submit" className="uk-button uk-button-primary">
            Save Preferences
          </button>
        </div>
        <div className="clear-button">
          <button
            type="button"
            onClick={this.props.clearCurrentProfile}
            className="uk-button uk-button-danger"
          >
            Reset Preferences
          </button>
        </div>
      </form>
    </div>
  );
}

export default connect(
  state => ({ profile: state.profile }),
  { clearCurrentProfile, getCurrentProfile }
)(withRouter(SelectOption));

SelectOption.propTypes = {
  clearCurrentProfile: PropTypes.func.isRequired,
  getCurrentProfile: PropTypes.func.isRequired,
  profile: PropTypes.shape({
    profile: PropTypes.arrayOf(PropTypes.object),
    profiles: PropTypes.arrayOf(PropTypes.object),
    loading: PropTypes.bool
  }).isRequired
};

动作/ index.js

import axios from "axios";
import { GET_PROFILE, PROFILE_LOADING, CLEAR_CURRENT_PROFILE } from "../types";

//Get current profile
export const getCurrentProfile = (preference, history) => dispatch => {
  // dispatch(setProfileLoading()); // not needed 
  return axios
    .get(`https://jsonplaceholder.typicode.com/${preference}`)
    .then(res => {
      dispatch({
        type: GET_PROFILE,
        payload: res.data
      });
      // history.push("/") // <== once data has been saved, push back to "/"
    })
    .catch(err =>
      dispatch({
        type: GET_PROFILE,
        payload: { err }
      })
    );
};

//Get current profile (async/await)
// export const getCurrentProfile = (preference, history) => async dispatch => {
//   try {
//     dispatch(setProfileLoading()); // not needed

//     const res = await axios.get(
//       `https://jsonplaceholder.typicode.com/${preference}`
//     );

//     dispatch({
//       type: GET_PROFILE,
//       payload: res.data
//     });

//     // history.push("/") // <== once data has been saved, push back to "/"
//   } catch (e) {
//     dispatch({
//       type: GET_PROFILE,
//       payload: { e }
//     });
//   }
// };

//Profile Loading
export const setProfileLoading = () => ({ type: PROFILE_LOADING });
//Clear Profile
export const clearCurrentProfile = () => ({ type: CLEAR_CURRENT_PROFILE });

减速器/ index.js

import { combineReducers } from "redux";
import { CLEAR_CURRENT_PROFILE, GET_PROFILE, PROFILE_LOADING } from "../types";

const initialState = {
  profile: [],
  profiles: [],
  loading: false
};

const profileReducer = (state = initialState, { type, payload }) => {
  switch (type) {
    case PROFILE_LOADING:
      return {
        ...state,
        loading: true
      };
    case GET_PROFILE:
      return {
        ...state,
        profile: payload,
        loading: false
      };
    case CLEAR_CURRENT_PROFILE:
      return {
        ...state,
        profile: []
      };
    default:
      return state;
  }
};

export default combineReducers({
  profile: profileReducer
});