当前位置:网站首页>[taro] applet picker dynamically obtains data

[taro] applet picker dynamically obtains data

2022-07-23 16:30:00 Web old monkey

In the applet ,picker Selectors provide several basic data formats , Such as time , date , Such area , It has basically met most of the needs .

But facing the customers and product managers who have opened their brains , The official has also left us a personalized space , stay picker Properties of the , Set the value to multiSelector, Then pass in a two-dimensional array data with unlimited length , To achieve a personalized multi selector .

When the amount of data is small , We can directly request the backend to send a message with a length of 3 Or a longer two-dimensional array , Insert into range in . But most linkage selector requirements are product categories , Customized regional data, etc , This kind of data is very large , And it's getting bigger and bigger , Request all data at once , Maybe not .

For example, a product classification data has a primary classification , second level , Not too many , But there are three levels , Four level classification , The amount of data increases as a set , Plus the relevant data carried , Maybe an interface is as light as 100 many kb, Heavy regulation 500+kb, At this time, it is necessary to obtain level by level .

One 、 Look at logic first

The logic is like this , The yellow square is assigned a value , Select below .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-WCdhYOZl-1658392588806)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d0790c78af4c436f8725d3888be77795~tplv-k3u1fbpfcp-zoom-in-crop-mark:4536:0:0:0.image?)]

Generally, when entering the page 2 States ,picker With or without value , That is, the new form is null , When modifying, there are values that need to be echoed .

Exhibition

Data interface getRangeData({parentCode:''}: Pass in code Get the lower level data list , The top-level data list is not returned

  • Anyway , The first step is through the interface provided by the back end (getRangeData({parentCode:''})) Get the first column of data c1.
  • If it's new , Directly through c1 Of the first value of code, the c1[0].code Pass in the interface to get secondary data c2, The same is true for the third column of data .
  • If it is a modification , Here comes a value like this , Corresponding to the selected values in the three columns , take value Of the first value of code Incoming interface , That is, through selected[0].code Get the second column of data , The third column does the same .
const selected = [
    {name: 'xxx',code: 0},
    {name: 'xxx',code: 01},
    {name: 'xxx',code: 012}
] 
  • All the data obtained are arrays , Combine the obtained data into a two-dimensional array and assign values , namely setRange([c1,c2,c3]), Now picker The basic functions of have been completed , It's ready to show .

operation

If you can show it , Users can click to operate , The function is half finished . As you scroll through each column , Still need to continue to get data , Dynamically modify the data of the next column , It's simpler here .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-yJV9i95R-1658392588807)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/cd90b550d4de4450b07a58d8ebe05e0c~tplv-k3u1fbpfcp-zoom-in-crop-mark:4536:0:0:0.image?)]

  • adopt onColumnChange Method , Get the currently scrolling column (column) And scroll to the index value (value), You can use the range[column][value].code Get and modify the value of the next column .
  • When you click OK , set out onChange Method , Get the index value selected in the current three columns (value), Through this index and range Data combination [range[0][value[0]],range[1][value[1]],range[2][value[2]]], You get the selected value .

So much logic as a whole , The most painful thing is the combination , More twists and turns .

Two 、 Code up

view part

When the value is empty , Please select , When there is a value, the selected value is displayed

<Picker
    mode="multiSelector"
    range={range}
    rangeKey="name"
    value={pickerValue.current}
    onChange={e => onChange(e)}
    onColumnChange={e => colChange(e)}
>
{selected ? (
      <Text>{selected.map(i => i.name).join()}</Text>
) : (
      <Text style={
   { color: "#686868" }}> Please select </Text>
)}
</Picker> 

js part

What is used here is taro-react Framework to implement this method , I use vue It has also been realized once , The code structure is basically not bad .

Initialization data

const pickerValue = useRef([0, 0, 0]); //  Index value of selector 
const [range, setRange] = useState<Array<any>>([]); //  The value of the selector 
const [selected, setSelected] = useState<Array<any>>([]); //  Selected value 

useEffect(() => {
    const init = async () => {
      const p = await getRangeData({});
      if (typeof params.selected === "undefined") {
        //  When the value is empty , Get the value of the next column by classifying the first value 
        const pp = await getRangeData({parentCode: p.data[0].code});
        const ppp = await getRangeData({parentCode: pp.data[0].code});
        setRange([p.data, pp.data, ppp.data]);
      } else {
        //  When there is value , Get the value of the next column by the selected value 
        const s = params.selected
        const pp = await getRangeData({parentCode: s[0].code});
        const ppp = await getAddrList({parentCode: c[1].code});
        setRange([p.data, pp.data, ppp.data]);
        setSelected(s);
      }
    };
    init();
}, []); 

Column selection

Now ,picker The default value of is successfully inserted , The next step is to dynamically obtain values when switching

 const colChange = e => {
    const { column, value } = e.detail;
    pickerValue.current[column] = value;
    if (column === 0) { //  Sliding column 1 
      let c0 = range[0][value]; //  Get the selected value of column 1 
      const p = await getRangeData({ parentCode: c0.code });
      setRange(v => [v[0], p.data, v[2]]);
    } else if (column === 1) {
      let c1 = range[1][value]; //  ditto 
      const p = await getRangeData({ parentCode: c1.code });
      setRange(v => [v[0], v[1], p.data]);
    }
  }; 

When pciker When switching , Get scrolling columns and positions , Then get the selected value of the current column through the index and get the following values

Here's a point to note , our range Data is an array , It's a reference type , If you use the following method to modify the value

setRange(v => {
    v[1] = p.data
    return v
}); 

It can be modified successfully , But the page refresh cannot be triggered , That is, the value of the second column will not change , You must use a deep copy method to trigger a page refresh

Confirm selection

Click OK to confirm , You can get the index values of three columns , And with the existing range One to one correspondence of data , Got it. 3 Selected values , Tell the selected value to be filtered into selected in , That is, all functions have been completed

 const onChange = e => {
    let v = e.detail.value;
    let s0 = range[0][v[0]];
    let s1 = range[1][v[1]];
    let s2 = range[2][v[2]];
    setSelected([
        {name: s0.name, code: s0.code}
        {name: s1.name, code: s1.code}
        {name: s2.name, code: s2.code}
    ]);
  }; 

summary

Function is relatively simple , But the first time I wrote it, there were many mistakes , It took half a day to write , It has been optimized for half a day , Spent a day on this little feature , Other projects in the future need to dynamically load lists , You can use this method .

原网站

版权声明
本文为[Web old monkey]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207231208484032.html