1 回答
TA贡献1998条经验 获得超6个赞
这是由于setState的async,也是hook造成的。
调用 Exchange_change 时,状态尚未设置,并且选择了先前的值。
尝试使用 useEffect 对homeSelect和所做的更改做出反应hedgeSelect:
const [homeSelect, setHomeSelect] = useState('Home');
const [hedgeSelect, setHedgeSelect] = useState('Hedge');
const [symbolSelect, setSymbolSelect] = useState('');
const [similarSymbols, setSimilarSymbols] = useState([]);
const handleHome = (event) => {
setHomeSelect(event.target.value);
};
const handleHedge = (event) => {
setHedgeSelect(event.target.value);
};
const handleSymbol = (event) => {
setSymbolSelect(event.target.value);
};
React.useEffect(exchange_change, [homeSelect, hedgeSelect]) // Here you listen to changes and update similarSymbols once changes are made.
const exchange_change = () => {
setSimilarSymbols([]);
//add symbols together from selected dropdowns
var allSymbols = response.content.symbols[homeSelect] + response.content.symbols[hedgeSelect];
console.log(allSymbols);
//sort the symbols
allSymbols = allSymbols.split(",");
var sort_arr = allSymbols.sort();
console.log(sort_arr);
//find duplicates
for(var i = 0; i < sort_arr.length-1; i++)
{
if(sort_arr[i + 1] == sort_arr[i]) {
setSimilarSymbols(similarSymbols => [...similarSymbols, sort_arr[i]]);
}
}
}
<FormControl dense>
<TextField
id="standard-select-currency"
select
label="Home"
className={classes.textField}
value={homeSelect}
onChange={handleHome}
SelectProps={{
native: true,
}}
helperText="Please select exchange"
>
<option>Home</option>
{response ? response.content.exchanges.map((option) => (
<option value={option}>
{option}
</option>
)) : <option>Data is loading...</option>}
</TextField>
</FormControl>
<FormControl dense>
<TextField
id="standard-select-currency"
select
label="Hedge"
className={classes.textField}
value={hedgeSelect}
onChange={handleHedge}
SelectProps={{
native: true,
}}
helperText="Please select exchange"
>
<option>Hedge</option>
{response ? response.content.exchanges.map((option) => (
<option value={option}>
{option}
</option>
)) : <option>Data is loading...</option>}
</TextField>
</FormControl>
<FormControl dense>
<TextField
id="standard-select-currency"
select
label="Symbols"
className={classes.textField}
value={symbolSelect}
onChange={handleSymbol}
disabled={homeSelect == 'Home' || hedgeSelect == 'Hedge'}
SelectProps={{
native: true,
}}
helperText="Please select the exchanges"
>
<option>Symbol</option>
{console.log(similarSymbols.map((element) => (element)))}
{response ? similarSymbols.map((option) => (
<option value={option}>
{option}
</option>
)) : <option>Data is loading...</option>}
</TextField>
</FormControl>
添加回答
举报