首页 > 解决方案 > React Redux 在 API 的表中显示数据

问题描述

目前,我的应用程序initialState在表中显示数据并且这些数据是硬编码的。我想在表格中显示我的 API 获取的数据。

这是我的 postReducer.js 文件:

var initialState = {
  employees: [
    { id: 1, name: 'jhon', age: '23'}, 
    { id: 2, name: 'doe', age: '24'}
  ]
};

var postReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_POST':
      return {
        ...state,
        employees: [...state.employees, action.data],
      };
    case 'EDIT_POST':
      return {
        ...state,
        employees: state.employees.map(emp => emp.id === action.data.id ? action.data : emp)
      };
      case 'DELETE_POST':
        console.log(action.data.id)
        return {
           ...state,
           employees: [...state.employees.filter((post)=>post.id !== action.data.id)],
        };
    default:
      return state;
  }
};


export default postReducer;

这是我的table.js文件

import React, {Fragment} from "react";
import { connect } from "react-redux";

class Table extends React.Component {
    onEdit = (item) => {  //Use arrow function to bind `this`
        this.props.selectedData(item);
    }

    onDelete = (id) => {
        const data = {
            id,
        }
        this.props.dispatch({ type: 'DELETE_POST', data });
    }
    render() {
        return (
            <Fragment>
                <thead>
                    <tr>
                        <th scope="col">Name</th>
                        <th scope="col">Age</th>
                        <th scope="col">Edit</th>
                        <th>Delete</th>
                    </tr>
                </thead>
                <tbody>
                {this.props.employees.map((item, index) => (
                    <tr key={index}>
                        <td>{item.name}</td>
                        <td>{item.age}</td>
                        <td>
                            <button
                                type="button"
                                onClick={() => this.onEdit(item)}>EDIT
                            </button>
                            <button
                                onClick={ () => this.onDelete(item.id) }>DELETE
                            </button>
                        </td>
                    </tr>
                ))}
                </tbody>
            </Fragment>
        );
    }
}

const mapStateToProps = (state) => ({ employees: state.employees });

export default connect(mapStateToProps)(Table);

这是我的 form.js 文件

import React, { Fragment } from "react"
import { connect } from 'react-redux'
const axios = require('axios');

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 
      id: this.props.selectedData.id, 
      name: this.props.selectedData.name, 
      age: this.props.selectedData.age,
    };
    this.onHandleChange = this.onHandleChange.bind(this);
    this.submit = this.submit.bind(this);
  }

  submit(event) {
    const data = {
      name: this.state.name, 
      age: this.state.age, 
      email: this.state.email
    };
    if (this.props.isEdit) {
      data.id = this.props.selectedData.id;
      console.log('edit', data);
      this.props.dispatch({ type: 'EDIT_POST', data })
    } else {
      // generate id here for new emplyoee
      this.props.dispatch({ type: 'ADD_POST', data })
    }
  }

  onHandleChange(event) {
    this.setState({
      [event.target.name]: event.target.value
    });
  }

  componentDidUpdate(prevProps) {
    if (prevProps.selectedData.age !== this.props.selectedData.age) {  //Check on email, because email is unique
      this.setState({ name: this.props.selectedData.name, age: this.props.selectedData.age })
    }
  }



  render() {
    return (
      <form>
        <div className="form-group">
          <input onChange={(event) => this.onHandleChange(event)} value={this.state.name} name="name" type="text" />
        </div>

        <div className="form-group">
          <input onChange={(event) => this.onHandleChange(event)} value={this.state.age} name="age" type="number" />
        </div>

        <button onClick={(event) => this.submit(event)} type="button">
          {this.props.isEdit ? 'Update' : 'SAVE'}
        </button>

      </form>
    );
  }
}

export default connect(null)(Form);

我想我需要处理 table.js 文件来实现,我尝试使用 componentDidmount 但我未能实现。

我正在使用 Axioshttp请求

这是带有 api 的请求片段:

axios.get('http://127.0.0.1:8000/api/v1/employee/')
    .then(function (response) {
      // handle success

    })
    .catch(function (error) {
      // handle error

    })
    .finally(function () {

    });

当我访问页面时,我不知道如何成功实现这一点,我应该看到包含来自 api 端点的数据的表。

任何人都可以帮我解决这个问题吗?

标签: reactjsreduxreact-redux

解决方案


在您的Table组件中,您可以使用componentDidMountAPI 调用,

componentDidMount(){
   axios.get('http://127.0.0.1:8000/api/v1/employee/')
    .then((response) => { //Use arrow function to auto bind `this`
      // handle success
      this.props.dispatch({ type: 'ADD_POST', response.data })   //considering response.data is the correct array 
    })
    .catch(function (error) {
      // handle error

    })
    .finally(function () {

    });
}

推荐阅读