在无数次尝试和轻微崩溃之后,我仍然无法通过我的React前端中的对象ID成功返回对象。即使数据根据Redux Dev Console和多个console.logs可用,我仍在Post Component中遇到相同的错误“无法读取属性'XXX”。我在下面提供了完整的Post Component以及所有其他相关代码,但这就是我的意思。...
renderPost() {
console.log(this.props.post);
// { _id: '5d1d93348a966c08c1f4bedb',
// title: 'Testing getPost',
// user: '5d1129e503da62058a95c481', }
console.log(this.props.post.title);
// ERROR Cannot read property 'title' of undefined
return (
<div className="content">
<h4 className="title">POST.TITLE HERE</h4>
</div>
);}
为什么我可以访问并返回this.props.post而不返回诸如this.props.post.title之类的东西?通过PostMan测试,后端一切正常,因此我肯定在前端搞砸了,这意味着无论是getPost动作创建者,GET_POST缩减器还是Post组件。
老实说,我认为它是在减速器或Post组件中的某个位置,但是我在旋转轮子的同时将头撞到墙上,所以将不胜感激。
如果我提供的信息不清楚或缺乏我的歉意。我是编程的新手,这是我第一次在这里发布文章,因此,请原谅任何在礼节上不可避免的灾难。
getPost Action Creator
export const getPost = _id => async dispatch => {
const res = await axios.get(`/api/posts/${_id}`);
dispatch({ type: GET_POST, payload: res.data });
};
getPost操作有效载荷
{ type: 'GET_POST',
payload: {
_id: '5d1d93348a966c08c1f4bedb',
title: 'Testing getPost',
user: '5d1129e503da62058a95c481', }}
GET_POST Reducer
import { GET_POSTS, GET_POST } from '../actions/types';
import _ from 'lodash';
export default (state = {}, action) => {
switch (action.type) {
case GET_POSTS:
return { ...state, ..._.mapKeys(action.payload, '_id') };
case GET_POST:
return { ...state.post, [action.payload._id]: action.payload };
default:
return state; }
结果发布状态
{ posts: {
'5d1d93348a966c08c1f4bedb': {
_id: '5d1d93348a966c08c1f4bedb',
title: 'Testing getPost',
user: '5d1129e503da62058a95c481',
}}}
发布组件
import React from 'react';
import { connect } from 'react-redux';
import { getPost } from '../actions';
class Post extends React.Component {
constructor(props) {
super(props);
this.state = {
post: {}
};}
componentDidMount() {
this.props.getPost(this.props.match.params.id);
// using params._ID instead results in CastError:
// Cast to ObjectId failed for value "{ _id: 'undefined' }"
// at path "_id" for model "Posts" }
renderPost() {
return (
<div className="content">
<h4 className="title">WANT TO RETURN POST.TITLE HERE</h4>
</div>
);}
render() {
return (
<div className="content-top">
<div>{this.renderPost()}</div>
</div>
);}}
const mapStateToProps = (state, ownProps) => {
return { post: state.posts[ownProps.match.params.id] };
// ._id at the end results in post being undefined
};
export default connect(
mapStateToProps,
{ getPost })(Post);
MongoDB SCHEMA
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const postSchema = new Schema({
title: { type: String, required: true },
user: { type: Schema.Types.ObjectId, ref: 'Users' }
});
const Post = mongoose.model('Posts', postSchema);
module.exports = Post;
MongoDB FID BY ID ROUTE
const mongoose = require('mongoose');
const Post = mongoose.model('Posts');
app.get('/api/posts/:id', async (req, res) => {
const post = await Post.findById({ _id: req.params.id });
res.json(post);
});
REDUX减少器
export default (state = {}, action) => {
switch (action.type) {
case GET_POSTS:
return { ...state, ..._.mapKeys(action.payload, '_id') };
// mapKeys is a function in Lodash that takes an array
// and returns an object. Whatever the value of ‘_id’
// is for an object inside an array is now the key for
// that object in a new state object.
case GET_POST:
return { ...state.post, [action.payload._id]: action.payload };
// Changing to action.payload.ID results in an undefined
// record being created in posts.
// { posts: {
// undefined: {
// _id: '5d1de8e47691dc12cc64b05c',
// title: 'xxxxxxxxx',
// user: '5d1129e503da62058a95c481' }}}
default:
return state;
}};
POSTLIST组件
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { getPosts } from '../actions';
class PostsList extends Component {
componentDidMount() {
this.props.getPosts(); }
renderPosts() {
return this.props.posts.map(post => {
return (
<div className="content" key={post._id}>
<h4 className="title">
<Link className="title" to={`/posts/${post._id}`}>
{post.title}
</Link>
</h4>
</div>
);});}
render() {
return (
<div className="content-top">
<div>{this.renderPosts()}</div>
</div>
);}}
const mapStateToProps = state => {
return {
posts: Object.values(state.posts)
};};
export default connect(
mapStateToProps,
{ getPosts }
)(PostsList);
答案 0 :(得分:0)
getPost操作是异步的
您可以像下面那样更新Post Component并尝试吗?
import React from 'react';
import { connect } from 'react-redux';
import { getPost } from '../actions';
class Post extends React.Component {
constructor(props) {
super(props);
this.state = {
loaded: false,
post: {}
};}
async componentDidMount() {
await this.props.getPost(this.props.match.params.id);
await this.setState({loaded: true});
}
renderPost() {
return (
<div className="content">
<h4 className="title">{this.props.post.title}</h4>
</div>
);}
render() {
return (
<div className="content-top">
<div>{this.state.loaded && this.renderPost()}</div>
</div>
);}}
const mapStateToProps = (state, ownProps) => {
return { post: state.posts[ownProps.match.params.id] };
// ._id at the end results in post being undefined
};
export default connect(
mapStateToProps,
{ getPost })(Post);