【问题标题】:How can i change the both value change and function call in a single onChange如何在单个 onChange 中同时更改值更改和函数调用
【发布时间】:2021-05-19 23:28:26
【问题描述】:

这里是代码,我想在city的值发生变化时同时调用apifetcher。怎么做??可能吗 城市的价值应该取代“q”的价值。之后,城市和 API 都将传递到另一个文件。我应该添加或删除什么。

import React, { useState } from "react";
import Cities from "./citylist";
import Autocomplete from "@material-ui/lab/Autocomplete";
import TextField from "@material-ui/core/TextField";
import Content from "./content";

const SearchBar = () => {
  const [city, setcity] = useState("");
  const [api, setapi] = useState(
    `http://api.openweathermap.org/data/2.5/forecast?q=Kurunegala,LK& mode=json&appid=5c4420d5c8a61c16e5ee37e4ca265763`
  );
  console.log(city);

  Content(city, api);

  const apiFtecher = () => {
    return setapi(
      `http://api.openweathermap.org/data/2.5/forecast?q=${city},LK&mode=json&appid=5c4420d5c8a61c16e5ee37e4ca265763`
    );
  };

  return (
    <div style={{ width: 300 }}>
      <Autocomplete
        freeSolo
        id="free-solo-2-demo"
        disableClearable
        options={Cities.map((option) => option.name)}
        renderInput={(params) => (
          <TextField
            {...params}
            label="city"
            margin="normal"
            variant="outlined"
            InputProps={{ ...params.InputProps, type: "search" }}
            onChange={(e) => setcity(e.target.value)}
            onBlur={(e) => setcity(e.target.value)}
          />
        )}
      />
    </div>
  );
};

export default SearchBar;

【问题讨论】:

  • 您想在每次更改文本字段时调用 API?或者你只想在模糊上调用它?
  • 我想在模糊上对其进行校准

标签: javascript reactjs api state use-state


【解决方案1】:

似乎不需要city 状态变量。

要在每次输入更改时调用apiFtecher[sic],您可以执行以下操作:

const apiFtecher = e => {
 const city = e.target.value;
 return (
  setapi(`http://api.openweathermap.org/data/2.5/forecast?q=${city},LK&mode=json&appid=5c4420d5c8a61c16e5ee37e4ca265763`)
  );
}

并将元素更新为:

<TextField
        {...params}
        label="city"
        margin="normal"
        variant="outlined"
        InputProps={{ ...params.InputProps, type: 'search' }}
        onChange={apiFtecher}
      />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多