Reactjs React-TypeError:无法读取未定义的属性
我有两个非常相似的React组件向Flask发出后端请求:Reactjs React-TypeError:无法读取未定义的属性,reactjs,flask,axios,Reactjs,Flask,Axios,我有两个非常相似的React组件向Flask发出后端请求: 反应 UserStatus.jsx class UserStatus extends Component { constructor (props) { super(props); this.state = { user:'', email: '', id: '', username: '', active: '', admin:
反应 UserStatus.jsx
class UserStatus extends Component {
constructor (props) {
super(props);
this.state = {
user:'',
email: '',
id: '',
username: '',
active: '',
admin: ''
};
};
componentDidMount() {
if (this.props.isAuthenticated) {
this.getUserStatus();
}
};
getUserStatus(event) {
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/auth/status`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
console.log(res.data)
console.log(res.data.data)
this.setState({
user: res.data.data.user,
email: res.data.data.email,
id: res.data.data.id,
username: res.data.data.username,
active: String(res.data.data.active),
admin: String(res.data.data.admin),
})
})
.catch((error) => { console.log(error); });
};
render() {
if (!this.props.isAuthenticated) {
return (
<p>You must be logged in to view this. Click <Link to="/login">here</Link> to log back in.</p>
)
};
return (
<div>
<h1 className="title is-1"><font color="#C86428">Current User</font></h1>
<hr/><br/>
<ul>
<li><strong><font color="#C86428">User:</font></strong><font color="white"> {this.state.coffeeshop} </font></li>
<li><strong><font color="#C86428">User ID:</font></strong><font color="white"> {this.state.id} </font></li>
<li><strong><font color="#C86428">Email:</font></strong><font color="white"> {this.state.email} </font></li>
<li><strong><font color="#C86428">Username:</font></strong><font color="white"> {this.state.username} </font></li>
<li><strong><font color="#C86428">Active:</font></strong><font color="white"> {this.state.active} </font></li>
<li><strong><font color="#C86428">Admin:</font></strong><font color="white"> {this.state.admin} </font></li>
</ul>
</div>
)
};
};
export default UserStatus;
class Seeds extends Component{
constructor (props) {
super(props);
this.state = {
user:'',
email: '',
id: '',
username: '',
active: '',
admin: ''
};
};
componentDidMount() {
if (this.props.isAuthenticated) {
this.getUserStatus();
}
};
getUserStatus(event) {
const options = {
url: `${process.env.REACT_APP_WEB_SERVICE_URL}/seeds`,
method: 'get',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.authToken}`
}
};
return axios(options)
.then((res) => {
console.log(res.data)
console.log(res.data.data)
this.setState({
user: res.data.data.user,
email: res.data.data.email,
id: res.data.data.id,
username: res.data.data.username,
active: String(res.data.data.active),
admin: String(res.data.data.admin),
})
})
.catch((error) => { console.log(error); });
};
render(){
return (
<div className="form">
<form action="http://localhost:5000/seeds" method="get, post">
</form>
</div>
);
}
}
export default Seeds;
Seeds在后端返回“数据”作为我的模板,Seeds.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Brandio Coffee Browser</title>
<link rel="stylesheet" href="/static/css/bootstrap.css">
<link rel="stylesheet" href="/static/css/mug.css">
<script src="/static/js/audiojs/audio.min.js"></script>
<script>
audiojs.events.ready(function() {
var as = audiojs.createAll();
});
</script>
....
烧瓶 种子.py
seeds_bp = Blueprint('seeds',
__name__,
template_folder='templates',
static_url_path='static')
@seeds_bp.route('/seeds', methods=['GET', 'POST'])
def seeds():
user = User.query.filter_by(id=1).first()
if user.x == []:
return render_template('seeds.html')
else:
# business logic
return render_template('seeds.html')
return render_template('seeds.html')
请允许我问: 1-为什么会有这种行为差异
2-如何正确呈现我的
seeds.html
后端模板页面?axios请求需要一个json响应,但它会收到一个html文件。查看您的客户端代码:
getUserStatus(event) {
//...
return axios(options)
.then((res) => {
console.log(res.data)
console.log(res.data.data)
this.setState({
user: res.data.data.user,
email: res.data.data.email,
id: res.data.data.id,
username: res.data.data.username,
active: String(res.data.data.active),
admin: String(res.data.data.admin),
})
})
// ...
您希望收到类似以下内容的json响应:
data = {
"user": "...",
"email": "...",
"id": "...",
"username": "...",
"active": "...",
"admin": "...."
}
因此,要接收JSON响应,您需要更改后端代码,如下所示:
from flask import jsonify
@seeds_bp.route('/seeds', methods=['GET', 'POST'])
def seeds():
user = User.query.filter_by(id=1).first()
if user.x == []:
# you need to change the '...' based to the user received from the
# database.
data = { "user": "...","email": "...","id": "...",
"username": "...","active": "...","admin": "...."}
return jsonify(data)
else:
# business logic
# you need to change the '...' based to the user received from the
#database.
data = { "user": "...","email": "...","id": "...",
"username": "...","active": "...","admin": "...."}
return jsonify(data)
data = { "user": "...","email": "...","id": "...",
"username": "...","active": "...","admin": "...."}
return jsonify(data)
在客户端部分,您需要记录响应并根据响应更改代码:
getUserStatus(event) {
//...
return axios(options)
.then((res) => {
console.log(res)
// ....
}
这个问题听起来更像是和烧瓶设置有关,而不是和react代码有关。我们是否确定您是从种子路由返回json对象,而不是从模板本身返回json对象?我在上面设置的Flask edit对您的问题有帮助吗?很好,谢谢。是否可以同时呈现模板和获取jsonified数据?是的,您可以接收jsonified数据,如data={“user”:“,“template”:“rendred template”},但问题是使用JSX语言而不是html模板。所以请确保模板与react兼容。
from flask import jsonify
@seeds_bp.route('/seeds', methods=['GET', 'POST'])
def seeds():
user = User.query.filter_by(id=1).first()
if user.x == []:
# you need to change the '...' based to the user received from the
# database.
data = { "user": "...","email": "...","id": "...",
"username": "...","active": "...","admin": "...."}
return jsonify(data)
else:
# business logic
# you need to change the '...' based to the user received from the
#database.
data = { "user": "...","email": "...","id": "...",
"username": "...","active": "...","admin": "...."}
return jsonify(data)
data = { "user": "...","email": "...","id": "...",
"username": "...","active": "...","admin": "...."}
return jsonify(data)
getUserStatus(event) {
//...
return axios(options)
.then((res) => {
console.log(res)
// ....
}