簡體   English   中英

在反應中按日期對表格進行排序,功能不起作用

[英]Sort table by date in react, function not working

我的排序功能不起作用,我想我可能需要對狀態做些什么? 我不是 100% 確定為什么它不起作用。 點擊很好,但是當我 console.log() 它時,數據數組似乎是空的。 在 render 方法中它 console.logs() 很好。

這是我的課:

    class Orders extends Component {
        constructor(props) {
          super(props);
          this.state = {
            ordersObject: {}, 
            sortingOrder: 'ASC',
          };

          this.sortBy.bind(this);
        }

        componentDidMount() {
          this.sortBy('delivery_date', 'DESC');
        }

        renderTableData(list) {
          return (
              <tbody>
                {list && list.map(item =>
                        <tr key={item.id}>
                          <td>{(new Date(item.delivery_date)).toLocaleDateString()}</td>
                          {/* <td>{item.cupcakes}</td> */}
                        </tr>
                )}
              </tbody>
          );
        }

        //getData function removed - getsData from API 

        //sort by DESC/ASC
        sortBy(sortedKey, sortedAs) {
            const data = this.state.orders;
            let sortingOrder = this.state.sortingOrder; 
            if(sortingOrder === sortedAs) {
                sortingOrder = 'DESC'; 
                data.sort((a,b) => b[sortedKey].localeCompare(a[sortedKey]))
            }
            else {
                sortingOrder = 'ASC'; 
                data.sort((a,b) => a[sortedKey].localeCompare(b[sortedKey]))
            }
            this.setState({data, sortingOrder })
        }

        render() { 

          let {ordersObject} = this.state;
          let {orders} = ordersObject;

          return ( 
            <table id="orders"> 
            <thead>
              <tr>
                <th onClick={() => this.sortBy('delivery_date', 'ASC')}>Date</th>
                <th>Description <input type="text"/></th>
              </tr>
            </thead>  
                {this.renderTableData(orders)}
            </table>
          );

        }
      }

解構后的數據是這樣的:

    orders: [ 
      {id: '000', 
      delivery_date: '2018-09-15T21:25:43.000Z', 
      cupcakes: ['peanutButterBase', 'vanillaFrosting', ['sprinkles', 'coconutFlakes']]},
      {id: '001', 
      delivery_date: '2019-09-15T21:25:43.000Z', 
      cupcakes: ['peanutButterBase', 'vanillaFrosting', ['sprinkles', 'coconutFlakes']]}
    ]
 this.state = { orders: [], ordersObject: {}, sortingOrder: 'ASC', };

this.state.orders

 componentDidMount() { this.getOrders(); this.sortBy('delivery_date', 'DESC'); }

getOrders() this.state.orders仍然是空的,因為獲取的數據...

this.setState({'ordersObject': results})

  • ... 僅分配給ordersObject ,而不分配給orders

  • this.sortBycomponentDidMount不能訪問新加載的數據

    • 因為它需要this.state.orders - 應該從ordersObject獲取數據並保存排序到orders (不是data )? this.setState({orders: sortedData,...
    • 您應該使用從sort返回的新對象 - 默認情況下,狀態通過引用進行淺層比較,它應該類似於let sortedData = [...data].sort(..因為data.sort(...返回相同的對象(排序到位);
    • 你不能在setState調用之后使用 state 中的數據 - 它是異步的 - 在setState使用回調或函數 - 請參閱文檔

render顯示“正確”的數據,因為

let {ordersObject} = this.state; let {orders} = ordersObject;
  • orders取自ordersObject不從(狀態更新后) this.state

我認為代碼需要一些修復:

  1. this.state.orders不正確,因為您正在使用此結構:
state: {
   ordersObject: {
      orders: [...] // from your API
   },
   sortingOrder: 'ASC'
}
  1. 當您訂購東西時,您正在執行this.setState({data, sortingOrder }) 但是你沒有使用this.state.data ,是嗎?

建議:

  1. 只需使用狀態中的orders
state = {
   orders: [...], //coming from the API
   sortingOrder: 'ASC'
}
  1. 以便在您的排序功能中,您可以執行this.setState({orders:data, sortingOrder})

示例改進代碼。 您可以根據您的要求進行更改。

export default class Orders extends React.Component {
  state = {
    order: [
      {
        id: "000",
        delivery_date: "2018-09-15T21:25:43.000Z",
        cupcakes: [
          "peanutButterBase",
          "vanillaFrosting",
          ["sprinkles", "coconutFlakes"]
        ]
      },
      {
        id: "001",
        delivery_date: "2018-09-15T21:25:43.000Z",
        cupcakes: [
          "peanutButterBase",
          "vanillaFrosting",
          ["sprinkles", "coconutFlakes"]
        ]
      },
      {
        id: "002",
        delivery_date: "2019-08-15T21:25:43.000Z",
        cupcakes: [
          "peanutButterBase2",
          "vanillaFrosting2",
          ["sprinkles2", "coconutFlakes2"]
        ]
      }
    ]
  };
  renderTableData() {
    return (
      <tbody>
        {this.state.order &&
          this.state.order.map(item => (
            <tr key={item.id}>
              <td>{new Date(item.delivery_date).toLocaleDateString()}</td>
              <td>{item.id}</td>
            </tr>
          ))}
      </tbody>
    );
  }
  sortBy = () => {
    let sorted = this.state.order.sort((a,b)=>{
      let date1 = new Date(a.delivery_date).toLocaleDateString();
      let date2 = new Date(b.delivery_date).toLocaleDateString();
      if (date1<date2)    return -1;
      else if(date1>date2) return  1;
      else   return  0;
    })
   this.setState({order:sorted})

  };
  render() {
    console.log(this.state.order)
    return (
      <table id="orders">
        <thead>
          <tr>
            <th onClick={this.sortBy}>Date</th>
            <th>
              Description <input type="text" />
            </th>
          </tr>
        </thead>
        {this.renderTableData()}
      </table>
    );
  }
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM