类型'{}'不能分配给类型'Readonly <iideascontainerprops>'类型'{}'中缺少属性'...'

时间:2018-09-12 20:08:28

标签: javascript reactjs typescript

我是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;

1 个答案:

答案 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 })
})