【发布时间】:2020-08-07 20:34:38
【问题描述】:
我正在尝试使用React、Redux 和Django 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(顾问的)的所有者。
我只想在组件表单中显示Counselor 的first_name 和last_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 组件中,我将调用getCounselors 和getUser 这两个动作。当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