【问题标题】:Retrieve object by id using the id of another object in React Component使用 React 组件中另一个对象的 id 通过 id 检索对象
【发布时间】:2020-08-07 20:34:38
【问题描述】:

我正在尝试使用ReactReduxDjango REST framework 构建一个网络应用程序。 API 提供了两种不同类型的用户。其中一个是名为Counselor 的模型,其所有者为auth.User,如下代码所示:

class Counselor(models.Model):
    owner = models.ForeignKey('auth.User',
                              related_name='counselors',
                              on_delete=models.CASCADE)
    # other fields...

Counselor 类将存储所有者 ID,API 提供和端点以通过其 ID 检索所有者,即 r'^users/(?P<pk>[0-9]+)/$' 和另一个端点以检索集合中的所有 Counselor 对象。

使用react-redux,我构建了一个组件,该组件将调用一个操作来检索所有Counselor 对象,并调用另一个操作来检索给定所有者ID(顾问的)的所有者。

我只想在组件表单中显示Counselorfirst_namelast_name。但是,该操作返回 undefined

下面的代码和我试图做的事情:

用户缩减器

import {
  // ...
  GET_USER,
} from "../actions/types";

const initialState = {
  token: localStorage.getItem("token"),
  isAuthenticated: false,
  isLoading: false,
  user: null,
};

export default function (state = initialState, action) {
  switch (action.type) {
    // ...
    case USER_LOADED:
    case GET_USER:
      return {
        ...state,
        isAuthenticated: true,
        isLoading: false,
        user: action.payload,
      };
    // ...
    default:
      return state;
  }
}

用户操作

// GET User
export const getUser = (id) => (dispatch, getState) => {
  axios
    .get(`/api/users/${id}/`, tokenConfig(getState))
    .then((res) => {
      dispatch({
        type: GET_USER,
        payload: res.data,
      });
    })
    .catch((err) => {
      dispatch(returnErrors(err.response.data, err.response.status));
    });
};

顾问减速器

import {
  GET_COUNSELOR,
  // ...
} from "../actions/types";

const initialState = {
  isRegistering: false,
  counselors: [],
};

export default function (state = initialState, action) {
  switch (action.type) {
    // ...
    case GET_COUNSELOR:
      return {
        ...state,
        isRegistering: false,
        counselors: action.payload,
      };
    // ...
    default:
      return state;
  }
}

辅导员行动

// GET Counselor
export const getCounselors = () => (dispatch, getState) => {
  axios
    .get("/api/counselors/", tokenConfig(getState))
    .then((res) => {
      dispatch({
        type: GET_COUNSELOR,
        payload: res.data,
      });
    })
    .catch((err) =>
      dispatch(returnErrors(err.response.data, err.response.status))
    );
};

React 组件中,我将调用getCounselorsgetUser 这两个动作。当getCounselors 被调用时,counselors 状态被填充,因此我可以检索 id。但是,当调用getUser(counselor.id) 时,对象是undefined

组件代码如下:

表单组件(我调用 getUser 的地方带有注释)

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

import { getCounselors } from "../../actions/counselors";
import { getUser } from "../../actions/auth";
import { postAppointment } from "../../actions/appointments";

export class Form extends Component {
  state = {
    title: "",
    date: "",
    start_time: "",
    end_time: "",
    location: "",
    description: "",
    counselor: "",
  };

  static propTypes = {
    counselors: PropTypes.array.isRequired,
    postAppointment: PropTypes.func.isRequired,
    getUser: PropTypes.func.isRequired,
  };

  componentDidMount() {
    this.props.getCounselors();
  }

  onChange = (e) => this.setState({ [e.target.name]: e.target.value });

  onSubmit = (e) => {
    e.preventDefault();

    const {
      title,
      date,
      start_time,
      end_time,
      location,
      description,
      counselor,
    } = this.state;

    const appointment = {
      title,
      date,
      start_time,
      end_time,
      location,
      description,
      counselor,
    };
    this.props.postAppointment(appointment);
    this.setState({
      title: "",
      date: "",
      start_time: "",
      end_time: "",
      location: "",
      description: "",
      counselor: "",
    });
  };

  render() {
    const {
      title,
      date,
      start_time,
      end_time,
      location,
      description,
      counselor,
    } = this.state;

    return (
      <div className="col-md-6 m-auto">
        <div className="card card-body mt-4 mb-4">
          <h2>Book an Appointment</h2>
          <form onSubmit={this.onSubmit}>
            {/* some divs ... */}
            <div className="form-group">
              <label>Counselor</label>
              <select
                type="text"
                className="form-control"
                name="counselor"
                onChange={this.onChange}
                value={counselor}
              >
                <option value="" disabled>
                  Choose...
                </option>
                {this.props.counselors.map((counselor) => (
                  <option key={counselor.id}>
                    {this.props.getUser(counselor.owner)} {/* HERE!!! */}
                  </option>
                ))}
              </select>
            </div>
            <div className="form-group">
              <button type="submit" className="btn btn-primary">
                Book
              </button>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

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

export default connect(mapStateToProps, {
  getCounselors,
  postAppointment,
  getUser,
})(Form);

你能建议吗?谢谢!

【问题讨论】:

    标签: reactjs redux react-redux axios


    【解决方案1】:

    据我所知,您没有从getUser 返回任何内容,这就是您收到undefined 的原因。您尝试同步获取异步数据的第二个问题是不正确的。可能你需要这两样东西:

    1. 制作 api 端点来获取用户数组,而不是向服务器发出许多请求
    2. componentDidUpdate提出这个请求

    实际上我不知道你的应用程序的架构,但看起来有点奇怪,你从服务器获取顾问数组,然后从每个对象获取 id 并再次发出请求,但也许你真的需要它(无论如何都要注意这一点)

    【讨论】:

    • 谢谢 - 我会试一试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 2019-10-05
    • 1970-01-01
    相关资源
    最近更新 更多