React Hooks-当我在另一个选择上选择一个选项时更改选择选项
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React Hooks-当我在另一个选择上选择一个选项时更改选择选项相关的知识,希望对你有一定的参考价值。
我是React的新手,当我从另一个选择中选择一个选项时,我想更改一个选择的选择选项。
我有此代码:
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);
}
我必须做些什么才能使Select 2在select 1的基础上进行更新?有人可以举个例子吗?对不起,我的英语
答案
您可以只在渲染第二个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>
))}
)
以上是关于React Hooks-当我在另一个选择上选择一个选项时更改选择选项的主要内容,如果未能解决你的问题,请参考以下文章
在 UICollectionView 选择上选择 UITableView
Element UI - VueJS - 在 IOS 上选择输入双击错误