繁体   English   中英

React 中的条件渲染不起作用,state 无法正常工作?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM