我有显示许多用户的页面。当我单击用户时,它会直接转到其页面。我希望该用户显示在此页面上,但出现错误:对模型“用户”的路径“ _id”的值“未定义”的对象ID转换失败
下面一些代码。
server.js:
app.get('/api/getAnotherUser/:id', getAnotherUser);
getAnotherUser.js:
const User = require('../models/User');
exports.getAnotherUser = async (req, res) => {
try {
const user = await User.findById(req.params.id).select('-password');
res.json(user);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
};
用户架构:
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
name: {
type: String,
}
});
module.exports = mongoose.model('user', UserSchema);
此页面的路径:
<PrivateRoute path="/user/" component={User} />
这是我在所有用户中映射的位置,键是_id,当我单击“打开”按钮时,它将重定向该特定用户的页面:
return this.state.users.map((user) => (
<div className="card" key={user._id}>
<div className="image-container">
<img src={user.image} alt="" />
</div>
<div className="card-details">
<p>{user.name}</p>
<p>{user.age}</p>
<p>{user.gender}</p>
<p>{user.location}</p>
</div>
<Link to={`/user/${user._id}`}>
<Button>Open</Button>
</Link>
</div>
));
我想要显示特定用户的页面(通过_id:]
在我的浏览器中: http://localhost:3000/user/5ed9d49c7e516616600eb693
在邮递员中,我通过_id成功获得用户: http://localhost:5000/api/getAnotherUser/5ed9d49c7e516616600eb693
MongoDB:“ _ id”:“ 5ed9d49c7e516616600eb693”
export class User extends Component {
constructor(props) {
super(props);
this.state = {
name: ''
};
}
componentDidMount() {
const token = localStorage.getItem('token');
if (token) {
this.setState({ loading: true });
axios.get(`/api/getAnotherUser/${this.props._id}`, { headers: { 'X-Auth-Token': token } }).then((res) =>
this.setState({
name: res.data.name,
})
);
}
}
render() {
return (
<div>
<h1>user: {this.state.name}</h1>
</div>
);
}
}
这是我得到错误的地方。通过_id显示的特定用户不会显示。这里出了什么问题?在Postman中,通过get请求,我可以通过_id来获取该用户,但是在我的应用程序中,我一定忘记了某些东西。有人可以指出在哪里吗?谢谢!
它说this.props._id
是未定义的,所以您要做的是
componentDidMount() {
const token = localStorage.getItem('token');
console.log(this.props._id) //check if this is undefined
if (token && this.props._id) {
...
}
}
如果this.props._id
在您的浏览器控制台中记录为未定义,那么您必须通过父组件传递_id,如果在父目录中未定义_id则>]