재우니의 블로그

redux 사용한 react.js 의 to-do 소스 CRUD 구현

 

 

C:\SourceSample\my-app>npm install --save redux

C:\SourceSample\my-app>npm install --save react-redux

 

 

 

index.js

 

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { createStore } from "redux";
import transactionReducer from "./reducers/transactionReducer";
import { Provider } from "react-redux";

if (localStorage.getItem("transactions") == null)
  localStorage.setItem("transactions", JSON.stringify([]));
let initialState = {
  currentIndex: -1,
  list: JSON.parse(localStorage.getItem("transactions")),
};
const store = createStore(transactionReducer, initialState);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

app.js

 

import React from "react";
import "./App.css";
import TransactionList from "./components/TransactionList";

function App() {
  return <TransactionList />;
}

export default App;

 

 

actions > transactionActions.js

 

export const insert = (data) => {
  return {
    type: "INSERT",
    payload: data,
  };
};

export const update = (data) => {
  return {
    type: "UPDATE",
    payload: data,
  };
};

export const Delete = (id) => {
  return {
    type: "DELETE",
    payload: id,
  };
};

export const updateIndex = (index) => {
  return {
    type: "UPDATE-INDEX",
    payload: index,
  };
};

 

reducers > transactionReducer.js

 

export const transactionReducer = (state, action) => {
  var list = JSON.parse(localStorage.getItem("transactions"));

  switch (action.type) {
    case "INSERT":
      list.push(action.payload);
      localStorage.setItem("transactions", JSON.stringify(list));
      return { list, currentIndex: -1 };

    case "UPDATE":
      list[state.currentIndex] = action.payload;
      localStorage.setItem("transactions", JSON.stringify(list));
      return { list, currentIndex: -1 };

    case "UPDATE-INDEX":
      return { list, currentIndex: action.payload };

    case "DELETE":
      list.splice(action.payload, 1);
      localStorage.setItem("transactions", JSON.stringify(list));
      return { list, currentIndex: -1 };
    default:
      return state;
  }
};

export default transactionReducer;

 

 

TransactionList.js

 

import React, { Component } from 'react'
import TransactionForm from './TransactionForm'
import { connect } from "react-redux";
import * as actions from "../actions/transactionActions"
import { bindActionCreators } from "redux";

class TransactionList extends Component {


    handleEdit = (index) => {
        this.props.updateTransactionIndex(index)
    }

    handleDelete = (index) => {
        this.props.deleteTransaction(index)
    }

    render() {
        return (
            <div>
                <TransactionForm />
                <hr />
                <table>
                    <tbody>
                        {this.props.list.map((item, index) => {
                            return <tr key={index}>
                                <td>{item.bAccountNo}</td>
                                <td>{item.bName}</td>
                                <td>{item.amount}</td>
                                <td><button onClick={() => this.handleEdit(index)}>Edit</button></td>
                                <td><button onClick={() => this.handleDelete(index)}>Delete</button></td>
                            </tr>
                        })}
                    </tbody>
                </table>
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        list: state.list
    }
}

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        updateTransactionIndex: actions.updateIndex,
        deleteTransaction: actions.Delete
    }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(TransactionList)

 

 

TransactionForm.js

 

import React, { Component } from "react";
import { connect } from "react-redux";
import * as actions from "../actions/transactionActions";
import { bindActionCreators } from "redux";

class TransactionForm extends Component {
  state = {
    ...this.returnStateObject(),
  };

  returnStateObject() {
    if (this.props.currentIndex === -1)
      return {
        bAccountNo: "",
        iFSC: "",
        bName: "",
        amount: "",
      };
    else return this.props.list[this.props.currentIndex];
  }

  componentDidUpdate(prevProps) {
    if (
      prevProps.currentIndex !== this.props.currentIndex ||
      prevProps.list.length !== this.props.list.length
    ) {
      this.setState({ ...this.returnStateObject() });
    }
  }

  handleInputChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    if (this.props.currentIndex === -1)
      this.props.insertTransaction(this.state);
    else this.props.updateTransaction(this.state);
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit} autoComplete="off">
        <input
          name="bAccountNo"
          placeholder="Account Number"
          onChange={this.handleInputChange}
          value={this.state.bAccountNo}
        />
        <br />
        <input
          name="iFSC"
          placeholder="IFSC"
          onChange={this.handleInputChange}
          value={this.state.iFSC}
        />
        <br />
        <input
          name="bName"
          placeholder="A/C Holder Name"
          onChange={this.handleInputChange}
          value={this.state.bName}
        />
        <br />
        <input
          name="amount"
          placeholder="Amount"
          onChange={this.handleInputChange}
          value={this.state.amount}
        />
        <br />
        <button type="submit">Submit</button>
      </form>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    list: state.list,
    currentIndex: state.currentIndex,
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators(
    {
      insertTransaction: actions.insert,
      updateTransaction: actions.update,
    },
    dispatch
  );
};

export default connect(mapStateToProps, mapDispatchToProps)(TransactionForm);

 

전체소스

 

 

src.zip
0.01MB