简体   繁体   English

React Hooks - 更改 select 选项当我 select 另一个 select 选项

[英]React Hooks - Change select options when I select an option on another select

I am new in React and I want to change select options of a select when I select an option from another select. I am new in React and I want to change select options of a select when I select an option from another select.

I have this code:我有这个代码:

component:零件:

 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);
     }

What I must to do to make the Select 2 to update based on select 1???我必须做什么才能使 Select 2 基于 select 1 更新??? Can anybody have an example?有人可以举个例子吗? Sorry for my english对不起我的英语不好

You could just filter before rendering the second select您可以在渲染第二个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>
     ))}
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM