React Native: 将所选项目的值传递给函数

huangapple go评论67阅读模式
英文:

react native: passing the value of selected items to a function

问题

我正在尝试实现一个来自react-native-dropdown-select-list库的MultipleSelectList,并将所选项目保存在@react-native-async-storage/async-storageAsyncStorage中。我实现了2个useState变量。首先是:

const [selected, setSelected] = useState([{}]);

这是一个包含{name: muscleGroup, value: id(s) of the exercise(s)}的列表(这是保存在viewDataList列表中的对象,见setExerciseViewLists)。我还实现了另一个useState变量:

const [selectedCount, setSelectedCount] = useState({
  Back: 0,
  Legs: 0,
  Chest: 0,
  // 其他...
});

我的想法是:当我从我的MultipleSelectList中调用handleSelect时,我会传递给它两个参数(val和item),val应该是运动的id(s),因为我在我的MultipleSelectList中定义了它(见MultipleSelectList),而item是来自viewDataList的一个列表项。

问题是:出于某种原因,val不是ID或ID列表,它是一个匿名函数:

function (val) {
   var temp = [].concat(val, [value]);
   return temp;
}

(我不太理解这是什么)。任何帮助都将不胜感激。

MultipleSelectList

{viewDataList.map((item, index) => (
  <MultipleSelectList
    data={item.list.map(listItem => ({
      value: listItem.id, // 这里
    }))}
    save="value"
    setSelected={val => handleSelect(val, item)}
    selected={selected.map(item => item.value)}
  />
))}

handleSelect/异步保存

const handleSelect = async (val, item) => {
    setSelectedCount(prevState => ({
      ...prevState,
      [item.name]: prevState[item.name] + 1, // item.name = muscleGroup
    }));

    setSelected(prevState => ([
      ...prevState,
      {
        name: item.name,
        value: val // val应该是ID(s)
      },
    ]));

    try {
      await AsyncStorage.setItem('selected', JSON.stringify([
        ...selected,
        {
          name: item.name,
          value: val,
        }
      ]));

      await AsyncStorage.setItem('selectedCount', JSON.stringify({
        ...selectedCount,
        [item.name]: selectedCount[item.name] + 1,
      }));

    } catch (e) {
      console.e('Error saving data to AsyncStorage:', e);
    }
};

setExerciseViewLists

const setExerciseViewLists = () => {
    let list = [];

    list.push(
      {.....},
      {
        num: 3,
        name: "muscleGroup",
        list: [{.....}, { id: "123", exercises : "something" }, {.....}]
      },
      {.....},
    );

  setViewDataList(list);
};
英文:

I am trying to implement a MultipleSelectList from this library react-native-dropdown-select-list. And I am saving the selected items in the AsyncStorage of @react-native-async-storage/async-storage. I implemented 2 useState variables: first const [selected, setSelected] = useState([{}]); this is a list of {name : muscleGroup, value : id(s) of the exercise(s)} (this is the object that is saved in the list of viewDataList [see setExerciseViewLists ]). The other useState variable that I have implemented is:

const [selectedCount, setSelectedCount] = useState({  // a list of the number of selected exercises per muscleGroup
    Back: 0,
    Legs: 0,
    Chest: 0,
    .....
  });

The idea: when I call handleSelect (see handleSelect) from my MultipleSelectList I give it 2 parameters (val and item) val should be the id(s) of the exercise(s) because I defined it as this in my MultipleSelectList (see MultipleSelectList) and the item is one list item from viewDataList.

The problem is: val is for some reason, not an ID or a list of IDs, it is an anonymous function:

function (val) {
   var temp = _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(new 
   Set([].concat(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(val),
   [value])));
   
   return temp;
}

(I don't really understand what this is). Any help would be appriciated.

MultipleSelectList

{viewDataList.map((item, index) =&gt; (
  &lt;MultipleSelectList
    data={item.list.map(listItem =&gt; ({
      value: listItem.id,                 //here
    }))}
    save=&quot;value&quot;
    setSelected={(val) =&gt; handleSelect(val, item)}
    selected={selected.map(item =&gt; item.value)}
  /&gt;
))}

handleSelect/Async saving

const handleSelect = async (val, item) =&gt; {

    setSelectedCount(prevState =&gt; ({
      ...prevState,
      [item.name]: prevState[item.name] + 1,   //item.name = muscleGroup
    }));

    setSelected(prevState =&gt; ([
      ...prevState,
      {
        name: item.name,
        value: val                             //val should be the ID(s)
      },
    ]));

    try {
      await AsyncStorage.setItem(&#39;selected&#39;, JSON.stringify([
        ...selected,
        {
          name: item.name,
          value: val,
        }
      ]));

      await AsyncStorage.setItem(&#39;selectedCount&#39;, JSON.stringify({
        ...selectedCount,
        [item.name]: selectedCount[item.name] + 1,
      }));

    } catch (e) {
      console.e(&#39;Error saving data to AsyncStorage:&#39;, e);
    }
};

setExerciseViewLists

const setExerciseViewLists = () =&gt; {
    let list = [];

    list.push(
      {.....},
      {
        num: 3,
        name: &quot;muscleGroup&quot;,
        list: [{.....}, { id: &quot;123&quot;, exercises : &quot;somthing&quot; }, {.....}]
      },
      {.....},
    );

  setViewDataList(list);
};

答案1

得分: 0

问题不在于您的数据,而在于您发送的自定义函数 handleSelect 作为 setSelected 属性。但是如果您查看库的文档,它明确说明了 setSelected 用于“设置将存储在本地状态中的选项值”。因此,您只能将选定的值存储在本地状态中。组件内的代码应该如下所示:

const [selectedValues, setSelectedValues] = useState();
    
return <MultipleSelectList
    data={SOME_DATA}
    save="value"
    setSelected={setSelectedValues}
  />;
英文:

The issue is not with your data but with the setSelected prop for which you are sending a custom function handleSelect. But if you see the library's documentation, it is clearly mentioned like setSelected is for For Setting the option value which will be stored in your local state. So you can only store the selected values in the local state. The code should be like below inside the component.

const [selectedValues, setSelectedValues] = useState();

return &lt;MultipleSelectList
    data={SOME_DATA}
    save=&quot;value&quot;
    setSelected={setSelectedValues}
  /&gt;

huangapple
  • 本文由 发表于 2023年2月6日 19:09:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75360538.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定