javascript 自然React:将选定项的值传递给函数

xmq68pz9  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(140)

我尝试从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({  // a list of the number of selected exercises per muscleGroup
    Back: 0,
    Legs: 0,
    Chest: 0,
    .....
  });

其思想是:当我从我的MultipleSelectList调用handleSelect(参见handleSelect)时,我给它两个参数(val和item)val应该是练习的id,因为我在我的MultipleSelectList中定义了它(参见MultipleSelectList),而item是viewDataList中的一个列表项。
问题是:由于某种原因,val不是一个ID或ID列表,它是一个匿名函数:

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;
}

(我真的不明白这是什么)。任何帮助都将不胜感激。

    • 多选列表**
{viewDataList.map((item, index) => (
  <MultipleSelectList
    data={item.list.map(listItem => ({
      value: listItem.id,                 //here
    }))}
    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 should be the 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);
    }
};
    • 设置练习视图列表**
const setExerciseViewLists = () => {
    let list = [];

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

  setViewDataList(list);
};
vxf3dgd4

vxf3dgd41#

问题不在于你的数据,而在于setSelected prop,你正在为它发送一个自定义函数handleSelect。但是如果你看到库的文档,它被清楚地提到,比如setSelected is for For Setting the option value which will be stored in your local state。所以你只能在本地状态下存储所选的值。代码应该如下所示,在组件内部。

const [selectedValues, setSelectedValues] = useState();

return <MultipleSelectList
    data={SOME_DATA}
    save="value"
    setSelected={setSelectedValues}
  />

相关问题