【问题标题】:Reactj, typescript Property 'setState' is missing in typeReactj,类型中缺少打字稿属性'setState'
【发布时间】:2017-11-18 00:33:52
【问题描述】:

我的反应组件出现 ts 错误。该组件运行良好,正在构建等,但是打字稿在 ide 内显示错误。不知道我需要如何声明它以消除错误。我试图在组件本身内部创建一个 setState 方法,但这会产生更多错误。

错误:(15, 19) TS2605:JSX 元素类型 'Home' 不是构造函数 JSX 元素的函数。类型中缺少属性“setState” “家”。

“打字稿”:“^2.3.4”,

“反应”:“^15.5.4”,

"react-dom": "^15.5.4",

!----

export class App extends React.Component<Props, State> {
  public state: State
  public props: Props

 constructor(props: Props) {
  super(props)
  this.state = {
    view: <Home />, <<<<
    } 

-- 为简洁起见删除了其余部分

export class Home extends React.Component<Props, State> {
public state: State;
public props: Props;

constructor(props: Props) {
    super(props)

}
  public render() {
    return <h1>home</h1>
  }
}

【问题讨论】:

  • 您不应将组件实例置于您的状态中。相反,你需要把这个组件的 props 放到你的 state 中,然后在 render 函数中创建它。
  • 哦,对了,我基本上是使用 this.setState({view:}) 绑定每个视图,然后在 render 方法下只渲染视图,例如: {this.state.view} .我想将它用作基本路由器,它正在工作,但会在 ide 中生成 ts 错误。
  • 不应该这样。国家需要保持简单。永远不要在 state 或 props 中保存组件
  • 好的,所以你建议我使用反应路由器或其他东西来管理这个?

标签: reactjs typescript


【解决方案1】:

这是一个如何使用状态和渲染组件的示例:

type HomeProps = {
    text: string;
}
class Home extends React.Component<HomeProps, void> {
    public render() {
        return <h1>{ this.props.text }</h1>
    }
}

type AppState = {
    homeText: string;
}
class App extends React.Component<void, AppState> {
    constructor() {
        super();

        this.state = {
            homeText: "home"
        };

        setTimeout(() => {
            this.setState({ homeText: "home after change "});
        }, 1000);
    }

    render() {
        return <Home text={ this.state.homeText } />
    }
}

如您所见,props 和 state 对象总是很简单,渲染方法负责创建实际的组件。
这样,react 就知道哪些组件发生了变化,以及 DOM 树的哪些部分应该更新。

【讨论】:

    【解决方案2】:

    有同样的问题,但我的问题是我导入 React 错误。

    使用 TypeScript 时的正确导入方法是使用import * as React from "react"。

    代码示例:

    import * as React from "react"
    import ReactDOM from "react-dom"
    
    class App extends React.Component<any, any> {
      render() {
        return (
          <div>Hello, World!</div>
        )
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("app"))
    

    注意:&lt;any, any&gt; 允许您在 React 组件中使用任何 props 和状态变量,但您通常应该自己定义这些以利用 TypeScript 的类型注释。

    【讨论】:

    • 或者如果你有一个变量 initialState 你可以type State = typeof initialState 得到所有的原子类型
    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 2017-12-22
    • 2021-09-23
    • 2023-02-07
    • 2021-04-29
    • 2013-09-17
    • 2019-05-02
    • 1970-01-01
    相关资源
    最近更新 更多