[英]Conditional Rendering in React won't work, state not working properly?
我試圖讓一個組件僅在我使用搜索按鈕時呈現。
下面的代碼是我當前的代碼
進行了更改,現在收到此錯誤。
錯誤] /home/holborn/Documents/Work/Portfolio/Data_Scraping/Eldritch/client/pages/index.tsx(21,19) 中的錯誤:21:19 找不到名稱“產品”。 19 | 接口 OutputProps { 20 | 搜索?:字符串
21 | 產品列表?:產品[] | ^ 22 | 23 | 24 | const Output: React.FC = ({ 搜索, productList }) => {
這是進行搜索時產品列表的數組
JSX element type 'void' is not a constructor function for JSX elements.
262 |
263 | return (
> 264 | <Output columns={columns} message={message} handleSearch={handleSearch} searchRef={searchRef} productList={productList}/>
| ^
265 |
266 | );
267 | }
您希望 output 組件具有productList
並作為道具進行searched
,但是您將其data
作為道具傳遞
其次,您必須直接定義接口,而不是 function
interface OutputProps {
searched?: string
productList?: Product[]
}
...
<Output searched={searched} productList={productList}/>
分解你的代碼:
function Output(searched,productList) {
if (!searched && !productList) {
return null;
}
return (
<div>
<div>
<p></p>
{/* <Chart data={productList} /> */}
</div>
<table className="table-auto">
<thead>
<tr>
<th className="px-4 py-2">Name</th>
<th className="px-4 py-2">Price</th>
<th className="px-4 py-2">Brand</th>
</tr>
</thead>
<tbody>
{productList.map((e, index) => (
<tr key={index}>
<td className="border px-4 py-2">{e.Product}</td>
<td className="border px-4 py-2">{e.Price}</td>
<td className="border px-4 py-2">{e.Brand}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
<Output data = {etc}/>
但是,這是無效的。 當您通過 JSX(即<Output/>
)調用組件時,React 將期望Output
使用單個props
參數調用,而不是多個 arguments。 (此外,您的etc
在這里未定義)
所以你可能打算這樣做:
// place your parameters inside an object, commonly referred to as "props"
function Output({ searched, productList }) {
而且,由於您使用的是 Typescript,因此您可以利用類型系統為您工作:
interface OutputProps {
searched?: string
productList?: Product[]
}
const Output: React.FC<OutputProps> = ({ searched, productList }) => {
// Typescript infers searched and productList typing here
if(!searched && !productList) {
return null;
}
...
}
當我們這樣做時,請格式化您的代碼。 查看Prettier以確保您的代碼保持一致且易於閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.