React Hooks - меняйте опции выбора, когда я выбираю опцию для другого выбора - PullRequest
1 голос
/ 05 ноября 2019

Я новичок в 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 обновлялся на основе select 1 ??? У кого-нибудь может быть пример? Извините за мой английский

1 Ответ

1 голос
/ 05 ноября 2019

Вы можете просто 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>
     ))}
)
...