如何使用axios在reactJS中获取数据?

时间:2018-01-22 21:56:37

标签: javascript reactjs rest axios

当我在JSON中获取数据时,我有reactJS类并尝试从中传递html:



class ProjectList extends React.Component {
    constructor(props) {
        super(props);

        this.state = {projects: []};
    }

    componentDidMount() {
        axios
            .get('http://localhost:8080/project')
            .then(res => this.setState({ projects: res.data.name }))
            .catch(err => console.log(err))
    }

    render() {
        return (
            this.state.projects.map((project) => {
                return (
                    <div>
                        <p> {project.name} </p>
                    </div>
                )
            })
        )
    }
}
&#13;
&#13;
&#13;

&#13;
&#13;
ReactDOM.render(
    <ProjectList />,
    document.getElementById('root')
);
&#13;
&#13;
&#13;

我可以解决什么是问题,因为在reactJS上有一些问题

1 个答案:

答案 0 :(得分:0)

您似乎正在存储res.data.name而不是res.data。含义this.state.projects被设置为单个name字符串。您应该将this.state.projects设置为res.data以获得完整的项目数组:

componentDidMount() {
    axios
        .get('http://localhost:8080/project')
        .then(res => this.setState({ projects: res.data }))
        .catch(err => console.log(err))
}