在react using post列表中显示帖子的创建者名称



我正在创建一个帖子列表,其中创建者的名字在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} />

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

EThttps://jsonplaceholder.typicode.com/users/undefined4042createError.js:17未捕获(承诺中(错误:请求失败,返回状态代码404在createError(createError.js:17(结算时(sett.js:19(在XMLHttpRequest.handleLoad(xhr.js:60(

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

<Postuser userId={post.userId} />

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

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

希望它能帮助

最新更新