首页 > 解决方案 > 如何使用 react-redux 显示所有用户的列表?

问题描述

我一直在尝试显示用户列表,但我没有找到错误的地方。有人可以帮帮我吗?如何显示用户列表。我已经附加了我从后端获得的响应。

这是代码:

用户列表.js

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

class ListUsers extends Component {
    componentDidMount(){
        this.props.listAllUsers()
    }
    usersList(){
        return this.props.users.map((user)=>{
            return (
                <div key={user.id}>
                    <div>{user.fullname}</div>
                    <div>{user.address}</div>
                    <div>
                        <button>Edit</button>
                    </div>
                    <div>
                        <button>Delete</button>
                    </div>
                </div>
            )
        })
    }
    render() {
        return (
            <div>
                <h1>Users List</h1>
                {this.usersList()}
            </div>
        )
    }
}

const mapStateToProps=(state)=>{
    console.log(state)
    return {users:state.users}
}

export default connect(mapStateToProps,{listAllUsers:listAllUsers})(ListUsers)

动作.js

import {ADD_USER,USERS_LIST} from '../actions/types'
import users from '../apis/users'
import { v4 as uuid } from 'uuid'

export const listAllUsers=()=>{
    return async (dispatch)=>{
        const response=await users.get('/users')
        dispatch({
            type:USERS_LIST,
            payload:response.data
        })
    }
}

userReducer.js

    import {USERS_LIST} from '../actions/types'
    
    const userReducer=(state=[],action)=>{
        switch(action.type){
            case USERS_LIST:
                return [...state,action.payload]
            default:
                return state
        }
    }
    export default userReducer

标签: reactjs

解决方案


推荐阅读