句柄更改,第二个功能取决于第一个

时间:2020-02-05 17:22:05

标签: javascript reactjs redux react-redux react-hooks

我在React中创建了一个选择器。

步骤如下:

  1. 从Mongodb加载数据(包含名称和相关查询的JSON)(使用“ queries_action”)
  2. 将名称注入选择器(变量“ selector_n_options”)
  3. 用户选择一个名称
  4. 将所选名称保存为Redux状态(使用“ load_action”)
  5. 从所选名称开始,检索相应的查询(变量“ query”)
  6. 启动一个Post API调用,该调用具有作为数据参数的var“ query”

现在,我需要在单个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);

0 个答案:

没有答案