【发布时间】:2021-10-17 11:21:53
【问题描述】:
我是基于函数(无类)的 React 新手,尝试使用 state redux 从组件中获取数组,并将其添加到新数组中,因为我只需要两个属性即可将元素添加到多个 Select 组件. 我尝试了不同的东西,但没有运气。我会接受任何帮助。这是我的代码:
const FormInfo = () => {
//reading an array from another component
const arrayFromOtherComponent = useSelector(state => state.otherComponente.array);
//creating a local state with empty array
const [state, setState] = useState([]);
//creating new state to add this object to the array state
const [ item, setItem ] = useState({
value: '',
label: ''
})
//looping arrayFromOtherComponent to get some properties and add to state
const callSelect = () => {
arrayFromOtherComponent.map( var => (
setItem({
value: '`{var.id}`', -> I cant' read the var object
label: '`{var.name}`' -> I cant' read the var object
}),
setState( state.concat(item) ) -> Is not updating the array state
));
}
//Calling function to update array
useEffect ( () => {
if(arrayFromOtherComponent){
callSelect() }
}, []);
.
.
.
//Using a Multiple Select to return the info
return (
.
.
.
<Select
isMulti
options={state} -> this should iterate the array state to show options
value={state.selectedOption}
onChange={handleChange}
closeMenuOnSelect={false}
/>
.
.
.
);
}
export default FormInfo;
【问题讨论】:
标签: arrays reactjs select state element