Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 财产';职位';不存在于类型';只读<;{}>';_Reactjs_Typescript_Next.js - Fatal编程技术网

Reactjs 财产';职位';不存在于类型';只读<;{}>';

Reactjs 财产';职位';不存在于类型';只读<;{}>';,reactjs,typescript,next.js,Reactjs,Typescript,Next.js,我正在将Nextjs与Typescript一起使用。 我想使用get请求获取帖子。我的这一行代码出现错误: render() { const {posts}= this.state 错误消息是: 类型“Readonly”上不存在属性“posts” 这是我的密码: import React, { Component } from 'react'; import axios from 'axios'; interface AbcState { posts: any[]; } export

我正在将Nextjs与Typescript一起使用。

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

render() {
const {posts}= this.state
错误消息是:

类型“Readonly”上不存在属性“posts”

这是我的密码:

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
import React,{Component}来自'React';
从“axios”导入axios;
接口AbcState{
职位:任何[];
}
导出类PostL扩展组件{
建造师(道具){
超级(道具)
此.state={
员额:[]
}
}
componentDidMount(){
axios.get()https://jsonplaceholder.typicode.com/posts')
。然后(响应=>{
console.log(响应)
this.setState({posts:response.data})
})
.catch(错误=>{
console.log(错误)
this.setState({errorMsg:'检索数据时出错'})
})
}
render(){
const{posts}=this.state
返回(
员额清单
{
长度?
posts.map(post=>{post.title}):null
}
)
}
}
导出默认PostL
像这样尝试:

export class PostL extends Component<any, any>
导出类PostL扩展组件

然后将道具和状态约束到实际形状。

如果希望组件在状态中具有值,则需要这样定义它

一般示例:

interface MyProps {
  ...
}

interface MyState {
  value: string
}

class App extends React.Component<MyProps, MyState> {
  ...
}
接口MyProps{
...
}
接口MyState{
值:字符串
}
类应用程序扩展了React.Component{
...
}

您在定义组件时是否尝试过声明道具和状态类型?是的,我尝试过:接口AbcState{posts:any[];}导出类PostL扩展组件{第一个泛型类型参数是props,而不是state。即使将其更改为props,错误仍然存在。我做了什么错事来解决问题,但下面的代码为什么不解决错误?不提及state和props不是一种坏做法吗?:interface props{posts:any[];导出类PostL扩展了component,因为在那里您断言组件的状态是
{}
类型。