我是React的新手,当我从另一个选择中选择一个选项时,我想更改一个选择的选择选项。
我有这个代码:
组件:
import React from 'react';
import {useDispatcher, useSelector} from 'react-redux';
import {getCounty, getLocality } from '../redux/actions/getData';
import NativeSelect from '@material-ui/core/NativeSelect';
export default function UserDetails() {
const dispatch = useDispatch();
const state = useSelector(state=>state);
const [county, setCounty ] = React.useState("");
const [locality, setLocality ] = React.useState("");
React.useEffect(() => {
dispatch(getCounty());
}, []);
return (
<>
#Select 1
<NativeSelect
value={county}
onChange={e => setCounty(e.targe.value))}
>
<option><option>
{state.county.map(el, key) => (
<option value={el.id} key={key}> {el.name}</option>
))}
</NativeSelect>
#Select 2
<NativeSelect
value={locality}
onChange={e=>setLocality(e.target.value)}
>
<option><option>
{state.locality.map(el, key) => (
<option value={el.id} key={key}> {el.name}</option>
))}
</NativeSelect>
</>
)
}
冗余操作:
export const getCounty = () => (dispatch) => {
axios.get(URL.COUNTY)
.then(res => dispatch({
type: "GET_COUNTY",
payload: res.data
}
.catch(err => {
console.log(err);
}
export const getLocality = (item) => (dispatch) => {
axios.get(URL.LOCALITY, item)
.then(res => dispatch({
type: "GET_LOCALITY",
payload: res.data
}
.catch(err => {
console.log(err);
}
我必须做些什么才能使Select 2在Select 1的基础上更新???有人能举个例子吗?对不起我的英语
在渲染第二个select
之前,您可以只使用filter
const countyIds = state.county.map(x => x.id)
//assuming that i.county exists, I don't know how it's called
const filteredLocality = state.locality.filter(i => countyIds.includes(i.county))
return(
{filteredLocality.map(el, key) => (
<option value={el.id} key={key}> {el.name}</option>
))}
)