首页 > 解决方案 > 如何在我的组件中获取用户 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.

标签: reactjsreduxreact-reduxredux-thunk

解决方案


推荐阅读