【发布时间】: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