React Hooks-当我在另一个选择上选择一个选项时更改选择选项

我是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>
 </>
)
}

redux-actions:

 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在选择1的基础上进行更新,我必须做什么??? 有人可以举个例子吗? 对不起,我的英语

kouder 回答:React Hooks-当我在另一个选择上选择一个选项时更改选择选项

您可以filter,然后再渲染第二个select

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>
     ))}
)
本文链接:https://www.f2er.com/3159515.html

大家都在问