React中的条件渲染无法正常工作,状态是否正常?

时间:2020-05-20 11:51:22

标签: javascript reactjs typescript next.js

我试图只在使用搜索按钮时才渲染组件。

下面的代码是我当前的代码

更新

进行更改, 现在收到此错误。

错误] /home/holborn/Documents/Work/Portfolio/Data_Scraping/Eldritch/client/pages/index.tsx(21,19)中的错误: 21:19找不到名称“产品”。 19 |接口OutputProps { 20 |搜索?:字符串

21 | productList ?:产品[] | ^ 22 | } 23 | 24 | const输出: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 | }

2 个答案:

答案 0 :(得分:2)

您希望输出组件具有productListsearched作为道具,但是您将其data作为道具传递

第二,您必须直接定义接口,而不是将其定义为函数

 interface OutputProps {
    searched?: string
    productList?: Product[]
}

...


<Output searched={searched} productList={productList}/>

答案 1 :(得分:1)

破坏代码:

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。 (此外,您的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,以确保您的代码保持一致并易于阅读。