【问题标题】:showing the creators name of the post in react using post list使用帖子列表在反应中显示帖子的创建者姓名
【发布时间】:2020-03-09 08:44:11
【问题描述】:

我在 react 和

https://jsonplaceholder.typicode.com 用户和帖子 API 的

我的动作文件

 export const fetchuser = (id) => async dispatch => {
        const response = await instance.get(`./users/${id}`)
        dispatch({
            type : "GET_USERS",
            payload :response.data
        })
    }

我的组件

import React, { Component } from 'react'
import {fetchuser} from '../actions'
import { connect } from 'react-redux'

class Postuser extends Component {
    componentDidMount(){
        this.props.fetchuser(this.props.userid)
    }
    render() {
        const user = this.props.users.find((user) => user.id === this.props.userId);
        if(!user){
            return null
        }
       return <div>{user.name}</div>
    }
}
const mapStateToProps = state => {
    return {
       users:state.users 
    }
}
export default connect(mapStateToProps,{fetchuser})(Postuser)

减速器

export default function userreducer(state=[], action) {
       switch(action.type){
        case"GET_USERS" :
        return [...state, action.payload]
        default : return state
       }
}

我使用这个组件的父组件

 <Postuser userId={post.userId} />

我收到此错误消息,请检查

ET https://jsonplaceholder.typicode.com/users/undefined 404 2createError.js:17 Uncaught (in promise) 错误:请求失败 状态码 404 在 createError (createError.js:17) 定居时 (settle.js:19) 在 XMLHttpRequest.handleLoad (xhr.js:60)

【问题讨论】:

    标签: reactjs api ecmascript-6 redux es6-promise


    【解决方案1】:

    好吧,你做错了什么,你将 userId 传递为

     <Postuser userId={post.userId} />
    

    但没有正确访问它,这样做

    componentDidMount(){
        this.props.fetchuser(this.props.userId) // I capital
    }
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多