我在React中创建了一个选择器。
步骤如下:
现在,我需要在单个handleChange中完成最后3点,但我不知道该怎么做。
我的代码:
const Load = state => {
//gets the queries stored in mongodb, starts automatically when I load the component
useEffect(() => {
new state.queries_action();
}, [state.queries_action]);
//this block manipulates the results of the previous operation, the names will be injected into the selector
try {
var key_api = state.reducer_queries.api_queries.data.map(obj => {
return {
name_api: obj["name"],
query_api: JSON.stringify(obj["query_json"])
};
});
} catch (err) {
key_api = {};
}
var key = _.groupBy(key_api, "name_api");
var name_uni = Object.keys(key);
var selector_n_options = [];
for (var i = 0; i < name_uni.length; i++) {
var temp_0 = {
value: i.toString(),
label: name_uni[i]
};
selector_n_options.push(temp_0);
}
//true only after you select a value, needed for the second action in handleSelect
try {
var query = JSON.parse(key[state.reducer_load.load][0].query_api);
} catch (err) {
query = {};
}
console.log(query); //works fine, after selecting a name, I can see the actual query
//PROBLEM: the first action writes the selected name to redux, THEN I NEED TO WAIT until query is compiled
const handleSelect = evt => {
new state.load_action(evt.label);
console.log(query); //PROBLEM: always empty
new state.show_query_action({
query_json: query
}); //PROBLEM: doesn't work properly since it depends on query
};
return (
<div>
<Box mt={11} pt={5} pb={10} bgcolor={white_col}>
<Container maxWidth="sm">
<Grid
container
direction="row"
justify="center"
alignItems="center"
spacing={3}
>
<Grid item xs={8}>
<Select
name="query_selector"
options={selector_n_options}
onChange={handleSelect}
placeholder="Seleziona query:"
maxMenuHeight={400}
theme={react_select_theme}
/>
</Grid>
</Grid>
</Container>
</Box>
</div>
);
};
export default connect(
state => {
return {
...state
};
},
{
queries_action,
load_action,
show_query_action
}
)(Load);