使用删除操作的React-redux问题

时间:2019-08-18 17:51:21

标签: reactjs redux react-redux

我正在用react-redux编写一个Crud应用程序,我已经成功完成readcreateupdate,现在我正在尝试学习实现delete的操作和我发现这很棘手,尽管它是最简单的一个。

这是我的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 = (index) => {
        this.props.selectedData(index);
    }
    render() {
        return (
            <Fragment>
                <thead>
                    <tr>
                        <th scope="col">Name</th>
                        <th scope="col">Age</th>
                        <th scope="col">Email</th>
                        <th>Edit</th>
                    </tr>
                </thead>
                <tbody>
                {this.props.employees.map((item, index) => (
                    <tr key={index}>
                        <td>{item.name}</td>
                        <td>{item.age}</td>
                        <td>{item.email}</td>
                        <td>
                            <button
                                type="button"
                                onClick={() => this.onEdit(item)}>EDIT
                            </button>
                            <button
                                onClick={ () => this.onDelete(index) }>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'

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, 
      email: this.props.selectedData.email 
    };
    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.email !== this.props.selectedData.email) {  //Check on email, because email is unique
      this.setState({ name: this.props.selectedData.name, age: this.props.selectedData.age, email: this.props.selectedData.email })
    }
  }



  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>

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

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

      </form>
    );
  }
}

export default connect(null)(Form);

这是我的postReducer.js文件:

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

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':
      return state.filter((post)=>post.id !== action.id);
    default:
      return state;
  }
};


export default postReducer;

这是App.js文件:

import React from "react"
import Table from "../components/table"
import Form from '../components/form'

class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
           selectedData: {name: '', age: '', email: ''},
           isEdit: false
        };
    }

    selectedData = (item) => {
       this.setState({selectedData: item,isEdit:true})
    }
    render() {
        return (
            <React.Fragment>   
              <Form selectedData={this.state.selectedData} isEdit={this.state.isEdit}/>          
            <table>
                <Table selectedData={this.selectedData} />
            </table>
            </React.Fragment>
        );
    }
}
export default App;

这是我的index.js文件:

import React from "react";
import ReactDOM from "react-dom";

import App from "../src/components/App";

import { Provider } from 'react-redux'

import { createStore } from 'redux'
import postReducer from '../src/postReducer'

const store = createStore(postReducer)


// if we don't subcribe, yet our crud operation will work
function onStateChange() {
  const state = store.getState();
  console.log(JSON.stringify(state, null, 2));
}

store.subscribe(onStateChange)

ReactDOM.render((
  <Provider store={store}>
      <App />
  </Provider>
), document.getElementById('app'))

除删除操作外,其他所有功能都工作正常,有人可以帮助我实现删除操作吗?我只是无法执行删除操作,如果有人修复我的删除操作,我们将不胜感激

谢谢

1 个答案:

答案 0 :(得分:1)

由于比较浅,我在这里认为redux更新似乎无法正常工作。尝试这样

return {
    ...state,
    employees: state.filter((post)=>post.id !== action.id);
  };