Yêu cầu thg 3 9, 2020 9:39 SA 1391 0 1
  • 1391 0 1
+1

Sửa thành table của ant.design

Chia sẻ
  • 1391 0 1

e có đoạn code như này, giờ e muốn table kia thành table của ant.design có phân trang từ api như ở dưới thì làm thế nào ạ. e cảm ơn

import React,{useState,useEffect} from 'react';
import {setUserToCustomer} from '../../../api-services/user-services';
import {listGroupUser} from '../../../api-services/sales-acc-management-services';
import {getUserSession} from '../../../utils/user-func';
import { Button,message,Popconfirm,Icon } from 'antd';
import { withRouter } from 'react-router';
import querystringify from 'querystringify';
import Pagination from '../../Pagination';

function ShowAdmin (props) {
    const user = getUserSession();
    const [showAdmin,setShowAdmin] = useState([]);
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [totalPage,setTotalPage] = useState(1);


    useEffect(()=>{
        async function fetchData(){
          const query = querystringify.parse(props.location.search);
          const _page = query.page;
          const _page_size = query.page_size;
          const response = await listGroupUser({
            group_name: "admin",
            page: _page,
            page_size:_page_size
          });
          setShowAdmin(response.data);
          setPage(response.paging.page)
          setPageSize(response.paging.page_size)
          setTotalPage(response.paging.totalPage);
        }
        fetchData()
    },[props.location]);


    const confirm = async(id) => {
      try {
        await setUserToCustomer(id);
        message.success('Change user to Customer Success');
        props.history.go(0);
      } catch (error) {
        throw error
      }
    }
    return <React.Fragment>
      <table className="table">
        <thead>
          <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Phone Number</th>
            <th>Role Change</th>
          </tr>
        </thead>
        <tbody>
        {(props.dataSearchAdmin !== null ? props.dataSearchAdmin : showAdmin).map((dt,index)=>{
          return <tr key={index}>
            <td>{dt.first_name !== null ? dt.last_name +' '+dt.first_name : dt.last_name}</td>
            <td>{dt.email}</td>
            <td>{dt.phone_number}</td>
            <td>{dt.id === user.user_id ? '' : 
              <Popconfirm 
                  placement="left" 
                  title="Are you sure change this user to Customer ?"
                  icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
                  onConfirm={()=>confirm(dt.id)} 
                  okText="Yes" 
                  cancelText="No"
              >
                <Button>Change to customer</Button>
              </Popconfirm>}
            </td>
          </tr>
          })}
        </tbody>
      </table>
      <Pagination
            page={page}
            pageSize={pageSize}
            totalPage={totalPage}
        />
    </React.Fragment>
}
export default withRouter(ShowAdmin);

1 CÂU TRẢ LỜI


Đã trả lời thg 3 9, 2020 9:44 SA
Đã được chấp nhận
+1
import { Table } from 'antd';
import reqwest from 'reqwest';

const columns = [
  {
    title: 'Name',
    dataIndex: 'name',
    sorter: true,
    render: name => `${name.first} ${name.last}`,
    width: '20%',
  },
  {
    title: 'Gender',
    dataIndex: 'gender',
    filters: [
      { text: 'Male', value: 'male' },
      { text: 'Female', value: 'female' },
    ],
    width: '20%',
  },
  {
    title: 'Email',
    dataIndex: 'email',
  },
];

class App extends React.Component {
  state = {
    data: [],
    pagination: {},
    loading: false,
  };

  componentDidMount() {
    this.fetch();
  }

  handleTableChange = (pagination, filters, sorter) => {
    const pager = { ...this.state.pagination };
    pager.current = pagination.current;
    this.setState({
      pagination: pager,
    });
    this.fetch({
      results: pagination.pageSize,
      page: pagination.current,
      sortField: sorter.field,
      sortOrder: sorter.order,
      ...filters,
    });
  };

  fetch = (params = {}) => {
    console.log('params:', params);
    this.setState({ loading: true });
    reqwest({
      url: 'https://randomuser.me/api',
      method: 'get',
      data: {
        results: 10,
        ...params,
      },
      type: 'json',
    }).then(data => {
      const pagination = { ...this.state.pagination };
      // Read total count from server
      // pagination.total = data.totalCount;
      pagination.total = 200;
      this.setState({
        loading: false,
        data: data.results,
        pagination,
      });
    });
  };

  render() {
    return (
      <Table
        columns={columns}
        rowKey={record => record.login.uuid}
        dataSource={this.state.data}
        pagination={this.state.pagination}
        loading={this.state.loading}
        onChange={this.handleTableChange}
      />
    );
  }
}

ReactDOM.render(<App />, mountNode);

phần này có cho customer paginate rồi mà nhỉ https://ant.design/components/table/#components-table-demo-ajax

 pagination={this.state.pagination}
Chia sẻ
Avatar Trần Xuân Hạnh @tranxuanhanh
thg 3 9, 2020 9:57 SA

e mới tập tọe thôi nên là cx ko biết đổi thế nào để nó chạy đc. E dùng axios.create(..).url để gọi api nên ko biết sửa thằng reqwest như thế nào

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí