【问题标题】:Property 'posts' does not exist on type 'Readonly<{}>''Readonly<{}>' 类型上不存在属性 'posts'
【发布时间】:2020-02-20 19:59:58
【问题描述】:

我正在使用 Nextjs 和 Typescript。

我想使用 Get 请求获取帖子。我的这行代码出现错误:

render() {
const {posts}= this.state

错误信息是:

类型“只读”上不存在属性“帖子”。

这是我的代码:

import React, { Component } from 'react';
import axios from 'axios';

interface AbcState {
  posts: any[];
}

export class PostL extends Component<AbcState>{

  constructor(props) {
    super(props)
    this.state = {
      posts: []
    }
  }

  componentDidMount() {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        console.log(response)
        this.setState({ posts: response.data })
      })
      .catch(error => {
        console.log(error)
        this.setState({ errorMsg: 'Error retrieving data' })
      })

  }

  render() {
    const { posts } = this.state
    return (
      <div>
        List of Posts
                    {
          posts.length ?
            posts.map(post => <div key={post.id}>{post.title}</div>) : null
        }
      </div>
    )
  }
}

export default PostL

【问题讨论】:

  • 你有没有尝试在定义组件时声明props和state类型?
  • 是的,我试过这个:interface AbcState { posts: any[]; } 导出类 PostL 扩展组件 {
  • 第一个泛型类型参数是 props,而不是状态。
  • 即使改成props,错误依旧存在。我做错了什么

标签: reactjs typescript next.js


【解决方案1】:

如果您希望您的组件在状态中具有价值,那么您需要像这样定义它。

一般示例:

interface MyProps {
  ...
}

interface MyState {
  value: string
}

class App extends React.Component<MyProps, MyState> {
  ...
}

【讨论】:

    【解决方案2】:

    试试这样:

    export class PostL extends Component<any, any>
    

    然后将你的道具和状态限制为实际形状。

    【讨论】:

    • 解决了问题,为什么下面的代码不能解决错误?不提 state 和 props 不是不好的做法吗? : 接口道具 { 帖子:任何 [];导出类 PostL 扩展 Component
    • 因为在那里你断言你的组件的状态是{}类型的。
    猜你喜欢
    • 2022-10-16
    • 2020-11-07
    • 2020-01-24
    • 2021-01-11
    • 1970-01-01
    • 2022-01-23
    • 2019-12-11
    • 2020-11-29
    • 2018-10-11
    相关资源
    最近更新 更多