Reactjs 财产';职位';不存在于类型';只读<;{}>';
我正在将Nextjs与Typescript一起使用。 我想使用get请求获取帖子。我的这一行代码出现错误: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
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扩展组件{}
类型。