如何在反应挂钩中传递输入字段

时间:2020-09-26 11:03:47

标签: reactjs react-hooks

我正在尝试通过搜索框传递输入字段,我可以在控制台中看到该值已更新,但未传递正确的值。背景信息我正在为社区建立免费的燃油价格手表。编码值是否可以通过传递

const [data, loading] = useAsyncRequest(10, 4172);

我的代码

AppAsync文件

import React, { useState, useEffect } from "react";
import PriceTable from "./tables/PriceTable";
import { useAsyncRequest } from "./hooks";


const AppAsync = () => {
  var suburb = 4172;
  const [price, setPrice] = useState(null);

  const [postCode, setPostCode] = useState(suburb);


  const submitValue = () => {
    const frmdetails = {
      'PostCode': postCode
    }
    suburb = frmdetails.PostCode;
    return suburb;
  }

  console.log(submitValue());
  const [data, loading] = useAsyncRequest(10, submitValue());

  useEffect(() => {
    if (data) {
      const formattedPrice = data.map((obj, i) => {
        return {
          siteId: i,
          fuelName: obj.fuelName,
          price: obj.price,
          address: obj.address,
          retailer: obj.retailer
        };
      });
      setPrice(formattedPrice);
    }
  }, [data]);


  return (
    <div className="container">
      <h1>Latest Fuel Price</h1>

      <hr />
      <input type="text" placeholder="Post Code" onChange={e => setPostCode(e.target.value)} />
      <button onClick={submitValue}>Submit</button>
      <div className="row">
        {loading || !price ? (
          <p>Loading...</p>
        ) : (
            <div className="seven columns">
              <h2>Fuel Price in your Area</h2>
              <PriceTable
                searches={price}
              />
            </div>
          )}
      </div>
    </div>
  );
};

导出默认AppAsync;

文件useAsyncRequest

import { useState, useEffect } from "react";

const useAsyncRequest = (amount, postCode) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      try {
        let headers = new Headers();
        headers.append('Accept', 'application/json');
        headers.append('Origin', 'https://localhost:3000');
        setLoading(true);
        const response = await fetch(
          `https://localhost:44396/api/Search?postCode=${postCode}`
        );
        const json = await response.json();

        setData(json.searches, setLoading(false));
      } catch (err) {
        console.warn("Something went wrong fetching the API...", err);
        setLoading(false);
      }
    };

    if (amount) {
      fetchData(amount);
    }
  }, [amount]);

  return [data, loading];
};

export default useAsyncRequest;

如果有人可以指出我做错了什么,我将立即作出反应。谢谢

1 个答案:

答案 0 :(得分:0)

在useAsyncRequest中,您仅在金额更改时触发useEffect,而在postCode更改时也需要这样做。

useEffect(()=>{...}, [amount, postCode]);

下面是一个有关api调用的模拟数据的示例:

import React from "react";
import "./styles.css";
import { useState, useEffect } from "react";

const useAsyncRequest = (amount, postCode) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await new Promise((resolve) => {
          setTimeout(() => resolve({
            json: () => new Promise((resolve) => resolve({searches: [
              {
                siteId: postCode,
                fuelName: 'blabla',
                price: amount,
                address: postCode,
                retailer: postCode
              }
            ]}))
          }), 1000);
        });
        const json = await response.json();

        setData(json.searches, setLoading(false));
      } catch (err) {
        console.warn("Something went wrong fetching the API...", err);
        setLoading(false);
      }
    };

    if (amount) {
      fetchData(amount);
    }
  }, [amount, postCode]);

  return [data, loading];
};

export default function App() {
  var suburb = 4172;
  const [price, setPrice] = useState(null);

  const [postCode, setPostCode] = useState(suburb);


  const submitValue = () => {
    const frmdetails = {
      'PostCode': postCode
    }
    suburb = frmdetails.PostCode;
    return suburb;
  }

  console.log(submitValue());
  const [data, loading] = useAsyncRequest(10, submitValue());

  useEffect(() => {
    if (data) {
      const formattedPrice = data.map((obj, i) => {
        return {
          siteId: i,
          fuelName: obj.fuelName,
          price: obj.price,
          address: obj.address,
          retailer: obj.retailer
        };
      });
      setPrice(formattedPrice);
    }
  }, [data]);


  return (
    <div className="container">
      <h1>Latest Fuel Price</h1>

      <hr />
      <input type="text" placeholder="Post Code" onChange={e => setPostCode(e.target.value)} />
      <button onClick={submitValue}>Submit</button>
      <div className="row">
        {loading || !price ? (
          <p>Loading...</p>
        ) : (
            <div className="seven columns">
              <h2>Fuel Price in your Area</h2>
              {JSON.stringify(price)}
            </div>
          )}
      </div>
    </div>
  );
}