🥹getDerivedStateFromProps thay thế cho componentWillReceiveProps ...

https://legacy.reactjs.org/docs/react-component.html#static-getderivedstatefromprops

https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html
https://www.geeksforgeeks.org/react-js-static-getderivedstatefromprops/

Đọc bài React Api Typescript Step By Step để biết thêm thông tin files

src\Pages\ProductActionPage.tsx

import React, { Component } from 'react';
import { Link, UNSAFE_RouteContext, useParams } from 'react-router-dom';
import { actAddProductRequest, actGetProductRequest } from '../actions';
import { connect } from 'react-redux';
var _ = require("lodash");
// function withParams(Component:any) {
//   return (props:any) => <Component {...props} params={useParams()} />;
// }
class ProductActionPage extends Component<any, any> {
  static contextType = UNSAFE_RouteContext;
  constructor(props: any) {
    super(props);
    this.state = {
      id: '',
      txtName: '',
      txtPrice: '',
      chkbStatus: false
    };
  }
  static getDerivedStateFromProps(nextProps: any, state: any) {
    if (nextProps && nextProps.itemEditing) {
      var { itemEditing } = nextProps;
      return {
        id: itemEditing.id,
        txtName: itemEditing.name,
        txtPrice: itemEditing.price,
        chkbStatus: itemEditing.status === true ? true : false
      }
    }
    return null;
  }
  onChange = (e: any) => {
    var target = e.target;
    var name = target.name;
    var value = target.type === 'checkbox' ? target.checked : target.value;
    this.setState({
      [name]: value
    });
  }
  componentDidMount() {
    let { matches }: any = this.context
    let routeMatch = matches[matches.length - 1];
    const params = routeMatch ? routeMatch.params : {};
    if (params?.id) {
      var id = params.id;
      this.props.onEditProduct(id);
    }
  }
  onSave = (e: any) => {
    e.preventDefault();
    var { id, txtName, txtPrice, chkbStatus } = this.state;
    var product = {
      id: id,
      name: txtName,
      price: txtPrice,
      status: chkbStatus
    };
    if (id) {
      // this.props.onUpdateProduct(product);
    } else {
      product.id = _.uniqueId;
      this.props.onAddProduct(product);
    }
  }
  render() {
    var { id, txtName, txtPrice, chkbStatus } = this.state;
    return (
      <div className="col-xs-6 col-sm-6 col-md-6 col-lg-6">
        <form onSubmit={this.onSave}>
          <div className="form-group">
            <label>Tên Sản Phẩm: </label>
            <input
              type="text"
              className="form-control"
              name="txtName"
              value={txtName ?? ""}
              onChange={this.onChange}
            />
          </div>
          <div className="form-group">
            <label>Giá: </label>
            <input
              type="number"
              className="form-control"
              name="txtPrice"
              value={txtPrice ?? 0}
              onChange={this.onChange}
            />
          </div>
          <div className="form-group">
            <label>Trạng Thái: </label>
          </div>
          <div className="checkbox">
            <label>
              <input
                type="checkbox"
                name="chkbStatus"
                value={chkbStatus ?? true}
                onChange={this.onChange}
                checked={chkbStatus}
              />
              Còn Hàng
            </label>
          </div>
          <Link to="/product-list" className="btn btn-danger mr-10">
            Trở Lại
          </Link>
          <button type="submit" className="btn btn-primary">Lưu Lại</button>
        </form>
      </div>
    );
  }
}
const mapStateToProps = (state: any) => {
  return {
    itemEditing: state.itemEditing,
  }
}
const mapDispatchToProps = (dispatch: any, props: any) => {
  return {
    onAddProduct: (product: any) => {
      dispatch(actAddProductRequest(product));
    },
    onEditProduct: (id: any) => {
      dispatch(actGetProductRequest(id));
    },
    // onUpdateProduct: (product:any) => {
    //   dispatch(actUpdateProductRequest(product));
    // }
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(ProductActionPage);

Last updated

Was this helpful?