【问题标题】:Why is axios being called twice in my program为什么在我的程序中两次调用 axios
【发布时间】:2019-03-14 17:20:57
【问题描述】:

我正在尝试通过 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 发布请求。它首先按预期填充首选项,但是它会立即进行另一个调用,并且首选项再次设置为 null。console.log(调用的)

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}

关于如何解决此问题的任何建议?

【问题讨论】:

  • 因为您在 onSubmit Methode 中调用它,而在 getCurrentProfile 函数中调用它
  • @evgenifotia 我认为它被调用了一次。你能解释一下这两个电话在哪里,所以我可以纠正它。谢谢
  • 我想先确定一件事。你能在export const getCurrentProfile = preference =&gt; dispatch =&gt; {my profileActionsclass之后做console.log("1111")

标签: javascript reactjs axios


【解决方案1】:

由于我无权访问您的所有代码(也无法对其进行调试),因此这是获取数据的更好方法。我的结构与您所拥有的非常接近,如果您按照工作示例进行操作,您应该能够消除问题。

我做了什么:

  1. onSubmit={this.onSubmit} 重命名为更标准的声明性 this.handleSubmit 方法
  2. handleSubmit 类方法中调用this.setState() 以删除selectedOption 值,然后在setState 回调中调用getCurrentProfile(value, history)(将value 替换为您的tempArray
  3. 将您的&lt;input type="submit" ... /&gt; 更改为&lt;button type="submit" ... /&gt;
  4. axios.get(...) 调用添加了return(我还包括getCurrentProfileasync/await 版本,这可能更容易理解——也可以将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 时,请避免使用模棱两可的类型,例如 objectarray,而是描述它们的结构。
  8. 由于 redux 的性质以及您设置组件的方式,您无需发送 setProfileLoading。您只需更新您的数据,连接的 React 组件就会更新以反映新的更改。在短时间内分别调度两个 redux 操作很可能会导致组件闪烁(将其视为在一秒钟内调用 this.setState() 两次——它会导致您的组件闪烁)。

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

SelectOption.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
};

actions/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 });

reducers/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
});

【讨论】:

  • 非常感谢先生
猜你喜欢
  • 2021-11-07
  • 2019-10-15
  • 1970-01-01
  • 2018-06-02
  • 2017-12-06
  • 1970-01-01
  • 2020-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多