“React前端变量在返回中未定义”

huangapple go评论66阅读模式
英文:

React frontend variable is undefined within return

问题

I'm fairly new to React and somewhat confused by why I can't access this variable. I assume it's a scope issue. Do I need to pass this variable to the return in another way? Exact error is: Line 47:16: 'filteredData' is not defined no-undef.

英文:

I'm fairly new to React and somewhat confused by why I can't access this variable I assume its a scope issue, do I need to pass this variable to the return in another way?
Exact error is: Line 47:16: 'filteredData' is not defined no-undef

import React, { useState, useEffect } from "react";

function App() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  useEffect(() => {
    fetch("http://localhost:8000/message")
      .then((res) => {
        if (!res.ok) {
          throw new Error("Request failed ${res.status}");
        }
        return res.json();
      })
      .then((data) => {
        setData(data.message);
      })
      .catch((error) => {
        setError(error);
      });
  }, []);
  // Filter the data to get specific values
  // const filteredName = data ? data.filter(item => item.name === 'name') : null;
  // const filteredPrice = data ? data.filter(item => item.price === 'price') : null;
  const FilteredData = ({ data }) => {
    const filteredData =
      data && Array.isArray(data)
        ? data.map((item) => ({
            name: item.name,
            symbol: item.symbol,
            price: item.quote && item.quote.USD && item.quote.USD.price,
          }))
        : [];
  };
  return (
    <div className="App">
      <h1>CoinBoy</h1>
      <p>
        Get the latest data from multiple trackers such as CoinMarketCap, ...
      </p>
      {error && <p>Error: {error.message}</p>}
      {!data ? (
        <p>Fetching Coins...</p>
      ) : (
        filteredData.map((item) => (
          <div key={item.symbol}>
            <h3>{item.name}</h3>
            <p>Symbol: {item.symbol}</p>
            <p>Price: {item.price}</p>
          </div>
        ))
      )}
    </div>
  );
}
export default App;

答案1

得分: 1

在你的代码中,你定义了FilteredData组件,但没有从中返回filteredData变量。为了在返回语句中访问filteredData,你需要按照以下方式更新你的代码:

import React, { useState, useEffect } from "react";

function App() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch("http://localhost:8000/message")
      .then((res) => {
        if (!res.ok) {
          throw new Error(`Request failed ${res.status}`);
        }
        return res.json();
      })
      .then((data) => {
        setData(data.message);
      })
      .catch((error) => {
        setError(error);
      });
  }, []);

  const FilteredData = ({ data }) => {
    const filteredData = data && Array.isArray(data)
      ? data.map((item) => ({
          name: item.name,
          symbol: item.symbol,
          price: item.quote && item.quote.USD && item.quote.USD.price
        }))
      : [];

    return (
      <>
        {filteredData.map((item) => (
          <div key={item.symbol}>
            <h3>{item.name}</h3>
            <p>Symbol: {item.symbol}</p>
            <p>Price: {item.price}</p>
          </div>
        ))}
      </>
    );
  };

  return (
    <div className="App">
      <h1>CoinBoy</h1>
      <p>Get the latest data from multiple trackers such as CoinMarketCap, ...</p>

      {error && <p>Error: {error.message}</p>}
      {!data ? (
        <p>Fetching Coins...</p>
      ) : (
        <FilteredData data={data} />
      )}
    </div>
  );
}

export default App;

更新后的代码,filteredData变量在FilteredData组件内部定义,并在组件的JSX内部返回。通过将数据属性传递给FilteredData组件,你可以在组件内部访问它并执行必要的过滤逻辑。

英文:

In your code, you define the FilteredData component, but you're not returning the filteredData variable from it. To access filteredData in your return statement, you need to update your code as follows:

import React, { useState, useEffect } from &quot;react&quot;;
function App() {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() =&gt; {
fetch(&quot;http://localhost:8000/message&quot;)
.then((res) =&gt; {
if (!res.ok) {
throw new Error(`Request failed ${res.status}`);
}
return res.json();
})
.then((data) =&gt; {
setData(data.message);
})
.catch((error) =&gt; {
setError(error);
});
}, []);
const FilteredData = ({ data }) =&gt; {
const filteredData = data &amp;&amp; Array.isArray(data)
? data.map((item) =&gt; ({
name: item.name,
symbol: item.symbol,
price: item.quote &amp;&amp; item.quote.USD &amp;&amp; item.quote.USD.price
}))
: [];
return (
&lt;&gt;
{filteredData.map((item) =&gt; (
&lt;div key={item.symbol}&gt;
&lt;h3&gt;{item.name}&lt;/h3&gt;
&lt;p&gt;Symbol: {item.symbol}&lt;/p&gt;
&lt;p&gt;Price: {item.price}&lt;/p&gt;
&lt;/div&gt;
))}
&lt;/&gt;
);
};
return (
&lt;div className=&quot;App&quot;&gt;
&lt;h1&gt;CoinBoy&lt;/h1&gt;
&lt;p&gt;Get the latest data from multiple trackers such as CoinMarketCap, ...&lt;/p&gt;
{error &amp;&amp; &lt;p&gt;Error: {error.message}&lt;/p&gt;}
{!data ? (
&lt;p&gt;Fetching Coins...&lt;/p&gt;
) : (
&lt;FilteredData data={data} /&gt;
)}
&lt;/div&gt;
);
}
export default App;

updated code, the filteredData variable is defined within the FilteredData component, and it is returned within the component's JSX. By passing the data prop to the FilteredData component, you can access it inside the component and perform the necessary filtering logic.

huangapple
  • 本文由 发表于 2023年6月26日 21:44:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定