【问题标题】:React .map is not a function but cannot pass arrayReact .map 不是函数但不能传递数组
【发布时间】:2020-07-26 11:21:08
【问题描述】:

我有我的应用根目录和一个延迟加载的组件。

应用根目录:

import Component from './app/components/component/component.lazy';

class App extends React.Component{

    stuff: stuffType[] = [1, 2 , 3];

    render() {
        return (
           <Component stuff={this.stuff}/>
        );
    }
}


export default App;

惰性组件:

import React, { lazy, Suspense } from 'react';
import {stuffType} from '../../dto/types';

const Lazycomponent = lazy(() => import('./component'));

const component = (props: {tanks: stuffType[]} & { children?: React.ReactNode; }) => (
  <Suspense fallback={null}>
    <Lazycomponent {...props} />
  </Suspense>
);

export default component;

组件:

const component: React.FC<any> = (stuff: stuffType[]) => {
    return(
       {stuff.map((stuff: stuffType, index: number) => {
           return (
              <div >

              </div>
           )
       })}
    )
}

上述代码在实时类型检查后没有错误,在运行控制台中也没有错误。

但是在浏览器中运行时我得到的错误是

TypeError: stuff.map 不是函数

好的。很好:

const component: React.FC<stuffType[]> = (stuff: stuffType[]) => {

现在在惰性组件中没有实时类型检查失败:

TS2740:类型 '{ stuff: stuffType[];孩子?:反应节点; }' 是 缺少类型“stuffType []”的以下属性:长度、流行、 push、concat 等 28 种。

当我给它的是一个数组时,它怎么能这么说?

【问题讨论】:

    标签: reactjs typescript react-component


    【解决方案1】:

    Props 是一个对象,而不是一个数组。

    interface Props {
      stuff: stuffType[]
    }
    
    const component: React.FC<Props> = props => {
        return(
           {props.stuff.map((stuff: stuffType, index: number) => {
               return (
                  <div >
    
                  </div>
               )
           })}
        )
    }
    

    【讨论】:

    • 谢谢,这行得通。因为stuffType 已经是一个界面,我没想到我需要第二个。
    猜你喜欢
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多