One background management time screening development experience

This requirement is an independent one, without its interface. In the upper left corner of the page, there is an antd time selection box with start and end times. On the right side of the page is a query button. After clicking the query button, the page will filter out the data that meets the standard

In fact, in addition to the date filter, there is also a type filter before, and the data on this page is transferred through the interface, and the request parameters in it are status, 0, 1, 2, 3. So you can just get the value of the type filter , directly put it in the parameter, so as to filter the rendering data of the page.

But this time selection box is just to filter one of the data, that is, the time, not to adjust the interface. So I thought about a general process first.
 

// 先声明一个变量,默认值为空,当时间选择之后,把起止时间戳放进变量里(参数1,开始时间,参数2,结束时间),查询按钮,点击的时候
//判断此变量是否为空,为空就直接调用页面渲染方法,否的话把渲染之后的参数循环,筛选。留下复合标准的数据,再调用dataSource方法,其参数就是之前留下来的值。最后每次修改时间时,更改dataSource。实现动态变化。其优先级高于类型筛选。

One of the key points summarized here is that there is a plug-in in dayjs that can compare dates , which will help me realize the logical judgment of screening later.
 

Start with the first step, declare a variable, oh yes, it is actually two variables

const [searchDateStart, setSearchDateStart] = useState<any>(2022 - 1 - 1) //展示選中時間内的數據(開始)
const [searchDateEnd, setSearchDateEnd] = useState<any>(2122 - 1 - 1) //展示選中時間内的數據(結束)

By the way, I also set default values ​​​​for them. This way even if they can display all the data normally at the beginning. First look at the functions in the date selection box


		<Form.Item
            name="range"
            label="发布时间"
            style={
   
   {
              marginTop: '24px'
            }}>
            <DatePicker.RangePicker
              format="YYYY-MM-DD "
              onChange={value => {
                dateOnChange(value)
              }}
            />
          </Form.Item>

That is, the onChange event is a callback when the current content changes. I conveniently passed in the selected value , and the format is the year, month, and day. That is to say, only the date is displayed (but his data still has time, minutes and seconds and needs to be processed by himself)

dateOnChange(value) now go to this function

//日期選擇
  const dateOnChange = async time => {
    console.log('time', time)
    if (time === null) {
      setSearchDateStart(2022 - 1 - 1)
      setSearchDateEnd(2122 - 1 - 1)
      const { data } = await getNotice(state)
      setDataSource(data)
    } else {
      // 設置選擇的開始時期
      setSearchDateStart(dayjs(time[0]._d).format('YYYY-MM-DD'))
      // 設置選擇的結束時期
      setSearchDateEnd(dayjs(time[1]._d).format('YYYY-MM-DD'))
    }
  }

time is the formal parameter of value

Log the time and print out two parameters

time (2) [Moment, Moment]

After some observation, the input time in the form is long like this


Moment
_d: Wed Jun 29 2022 10:10:05 GMT+0800 (中国标准时间) {}
_isAMomentObject: true
_isUTC: false
_isValid: true
_locale: Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate: 'Invalid date', _dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: ƒ, …}
_pf: {empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -2, charsLeftOver: 0, …}
[[Prototype]]: Object

Why is there an if judgment ? Because when the clear button is clicked, the time value null . At this time, it is only necessary to display all the data.

time : null

Anyway, you can ignore him now

Look inside the else

 else {
      // 設置選擇的開始時期
      setSearchDateStart(dayjs(time[0]._d).format('YYYY-MM-DD'))
      // 設置選擇的結束時期
      setSearchDateEnd(dayjs(time[1]._d).format('YYYY-MM-DD'))
    }

There is a start time and an end time. The format is 'YYYY-MM-DD',

Now let me introduce the query button

<Button type="primary" onClick={() => getNoticeData()}>
  查询
</Button>

What the getNoticeData() method originally does is to update the table data and call the data interface
 

Now getNoticeData() changed to this

  // form數據更新
  const getNoticeData = useCallback(async () => {
    const { data } = await getNotice(state)
    setDataSource(data)
    if (!(searchDateStart === 2022 - 1 - 1 && searchDateEnd === 2122 - 1 - 1)) {
      dataChange(data)
    }
  }, [state, searchDateStart, searchDateEnd, form])

The dependencies add the start time and end time . As long as one of them is updated , the function will be reloaded and when the value of the time selection box changes, the above function of setting the start and end time will be called. You can basically achieve synchronization
 

Look at the logic inside

const { data } = await getNotice(state)
setDataSource(data)

These two sentences are the original content. The realized function is to set the table data . The source of the data is called from the background.
 

if (!(searchDateStart === 2022 - 1 - 1 && searchDateEnd === 2122 - 1 - 1)) {
      dataChange(data)
    }

This sentence is what I changed for this task.

It is judged whether the start and stop values ​​are not the original values. As long as it is not, it must be changed by the user. Then call the dataChange function
 

Here comes the key screening part

 // 日期筛选
  const dataChange = dataChange => {
    console.log('dataChange', dataChange)
    dataChange.data.map((item, index) => {
      if (dayjs(dayjs(item.publish_time * 1000).format('YYYY-MM-DD')).isBetween(searchDateStart, searchDateEnd, 'day', '[]')) {
        console.log('第' + index + '列符合条件' + '此条内容为' + item)
        console.log(item)
        timeArray.push(item)
      }
    })
    console.log(timeArray)
    setDataSource({ msg: '', code: 0, data: timeArray })
    console.log(dataSource)
    setTimeArray([])
  }


The parameter is the data value just now, and the name here is dataChange .

The function of this is to filter and push into a new array, and the content of that array is the content to be kept
and printed.

dataChange {msg: '', code: 0, data: Array(5)}code: 0data: (5) [{…}, {…}, {…}, {…}, {…}]msg: ""[[Prototype]]: Object

At that time, after careful observation, it was actually the basic page data. Inside data is the array we need to modify

Every data is like this

0: {id: 77, publish_time: 1656518400, publish_data: 'hhh', state: 0}

For example, article 0 is long like this

As you can see, the publish_time here is a ten-digit timestamp. I have been working on the details of the comparison for a long time and tried it. All converted to timestamp, it turned out that there is a problem. The data of the time selector is the kind of Chinese standard time. After converting to timestamp, it is found that the digit is 13, but it is wrong to add and subtract the time. In the end, I gave up this method. After asking my brother, I learned that dayjs can choose the interval
 

So it is used together with the dayjs plugin. The plugin I use here is between

bring in first

import isBetween from '../../../node_modules/dayjs/plugin/isBetween'

This needs to find the path in dayjs

Again

  dayjs.extend(isBetween)

This is ready to use.

The last is to turn both time numbers into a date format,
and this has just been done

	// 設置選擇的開始時期
      setSearchDateStart(dayjs(time[0]._d).format('YYYY-MM-DD'))
      // 設置選擇的結束時期
      setSearchDateEnd(dayjs(time[1]._d).format('YYYY-MM-DD'))

Looking back at the main judgment logic

 dataChange.data.map((item, index) => {
      if (dayjs(dayjs(item.publish_time * 1000).format('YYYY-MM-DD')).isBetween(searchDateStart, searchDateEnd, 'day', '[]')) {
        console.log('第' + index + '列符合条件' + '此条内容为' + item)
        console.log(item)
        timeArray.push(item)
      }
    })

isBetween is a plug-in api of dayjs . The last parameter determines whether it is included or not. '[]' is included. The penultimate parameter determines which date node to compare to. Here is "day", which is the day
 

timeArray is a constant created by yourself, and an array is stored here, all eligible arrays .
 


Next, assign the value to the new dataSource after the loop ends and reset the TimeArray after rendering. So that the next time you select the time, you will not directly continue to add new arrays
 

   console.log(timeArray)
    setDataSource({ msg: '', code: 0, data: timeArray })
    console.log(dataSource)
    setTimeArray([])

Ok, after setDataSource you're done

Guess you like

Origin blog.csdn.net/qq_53563991/article/details/125502606