reactjs - 如何在我的组件中获取用户 ID 以便能够分派到操作
问题描述
我想显示用户提要和他的帖子。我打算从 UserPosts 组件的 componentDidMount 分派一个动作,但现在没有 id。该组件如下所示:
import React, { Component } from "react"
import { getUserposts } from "../actions/userActions"
class UserPosts extends Component {
componentDidMount() {
//////
}
render() {
return (
<div className="card">
<div className="card-content">
<div className="media">
<div className="media-left">
<figure className="image is-48x48">
<img
src="https://bulma.io/images/placeholders/96x96.png"
alt="Placeholder image"
/>
</figure>
</div>
<div className="media-content">
<p className="title is-4"></p>
<p className="subtitle is-6"></p>
</div>
</div>
<div className="content">Insert Bio</div>
</div>
</div>
)
}
}
export default UserPosts
和这样的动作:
export const getUserposts = (id) => {
return async dispatch => {
dispatch({
type: "FETCHING_POSTS",
})
try {
const res = await axios.get(
`http://localhost:3000/api/v1/users/posts/${id}`, {
headers: {
"Content-Type": "application/json"
}
}
)
dispatch({
type: "FETCHING_POSTS_SUCCESS",
data: res.data
})
} catch(err) {
dispatch({
type: "FETCHING_POSTS_ERROR",
data: { error: res.data.error}
})
}
}
}
现在我如何获得身份证?我有一条路线可以为我提供当前登录的用户。是/me
路线。我已经在我的 . 之上进行了设置App.js
,因此它在每次刷新时都会运行。那么,是否可以先调度/me
路由,获取 id,然后再次调度getUserPosts
操作。如何从 componentDidMount 分派两个动作?
这是否可行。
componentDidMount() {
const authToken = localStorage.getItem("authToken");
this.props.dipsatch(getCurrentUser(authToken)) // this will return the current user object
this.props.dispatch(getUserPosts(id)) // i will probably get this id from the props from the
//redux store
}
Please tell how can I approach this? Thanks.
解决方案
推荐阅读
- java - 机器人按键无法在无头模式下工作
- react-native - 如何创建带断点的圆形滑块?
- python - 当我尝试导入 lxml.html 时出现导入错误
- python - 从 django ORM 检索查询
- java - 如何隐藏 s3 存储桶并从 Html 文件中访问密钥凭证
- r - 如何在R中将逻辑运算符设置为函数的参数
- ios - 在日期设置为 Jan 1, 1 时使用 iOS SDK DateFormatter 时的时间输出不符合预期
- c# - 是否需要拥有服务用户帐户才能将 ASP.NET Core 应用程序部署为 Windows 服务?
- java - Hibernate 的 @JoinFormula 检索子列表会导致 ClassCastException
- typescript - 在 typedoc 中自定义主题破坏搜索功能