我是TypeScript的新手,在尝试运行此代码段时遇到了一些问题。
错误
错误消息是:
无法编译
13,8): Type '{}' is not assignable to type 'Readonly <IIdeasContainerProps>'.
Property 'ideas' is missing in type '{}'.
代码
import axios from 'axios';
import * as React from 'react';
interface IdeasContainerState {
ideas: Array<any>;
}
interface IIdeasContainerProps {
ideas: Array<any>;
}
class IdeasContainer extends
React.Component<IIdeasContainerProps,IdeasContainerState> {
constructor(props:IIdeasContainerProps) {
super(props)
this.state={ideas:this.props.ideas}
}
render() {
return (
<div>
{this.state.ideas.map((idea:any) => {
return(
<div className="tile" key={idea.id} >
<h4>{idea.title}</h4>
<p>{idea.body}</p>
</div>
)
})}
</div>
);
}
componentDidMount() {
axios.get('http://localhost:3001/api/v1/ideas.json')
.then(response => {
console.log(response)
this.setState({ideas: response.data})
})
.catch(error => console.log(error))
}
}
export default IdeasContainer;
答案 0 :(得分:1)
您的axios
通话似乎是您的错误。像这样使用axios.get()
的通用版本:
axios.get<Array<any>>('...').then(response => {
// response.data will now be inferred as Array<any> instead of {}
this.setState({ ideas: response.data })
})