React Redux在API表中显示数据

时间:2019-08-25 12:49:09

标签: reactjs redux react-redux

当前,我的应用程序在表中显示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,但是实现失败。

我正在使用Axios进行http请求

这是带有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端点的数据的表。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

Table组件中,您可以使用componentDidMount进行API调用,

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 () {

    });
}