我正在尝试使用Redux中的数据实现materialuiselect组件,以允许在刷新期间保持选择。
我在Redux内部有两个数据数组:
sourceTags
数组,这是我的可单击菜单选项列表,以及
selectedTags
数组,其中包括选定的选项(用户单击的选项)。Material UI组件的api是
here
组件如下所示:
import React, { useEffect, useState } from 'react';
import { Select, Input, MenuItem } from "@material-ui/core";
import { useDispatch, useSelector } from "react-redux";
import { setTags } from "../actions/search";
const MultiChipSelect = ({ source }) => {
const dispatch = useDispatch();
const selectedTags = useSelector(state => state.search.tags);
const sourceTags = useSelector(state => state.settings[source].tags);
const handleTagClick = async (e) => {
dispatch(setTags(e.target.value)); // Sets my searchTags list in Redux.
// The e.target.value is an array of objects, or an empty array.
};
return (
<Select
multiple
value={selectedTags}
onChange={handleTagClick}
input={<Input id="select-multiple" />}
>
{sourceTags.map(val => (
<MenuItem key={val._id} value={val}>
{val.data}
</MenuItem>
))}
</Select>
);
}
export default MultiChipSelect;
该组件至少部分工作。以下是我做出选择时的样子:
问题是,当我刷新页面时,selectedTags数组没有显示在组件中。对象确实显示在“选择”组件内,但不显示:
useState
钩子是不是,按照例子?
使用状态
钩子。请记住,这不会在刷新之间保留选择:
import React, { useState } from 'react';
import { Select, Input, MenuItem } from "@material-ui/core";
import { useSelector } from "react-redux";
const MultiChipSelect = ({ source }) => {
const sourceTags = useSelector(state => state.settings[source].tags);
const [tags, setTags] = useState([]);
const handleTagClick = async (e) => {
setTags(e.target.value); // Sets my tags list.
};
return (
<Select
multiple
value={tags}
onChange={handleTagClick}
input={<Input id="select-multiple" />}
>
{sourceTags.map(val => (
<MenuItem key={val._id} value={val}>
{val.data}
</MenuItem>
))}
</Select>
);
}
export default MultiChipSelect;