简体   繁体   中英

how to get data in the reactJS using axios?

I have reactJS class when I get a data in JSON and try to trasfrom it for 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> ) }) ) } } 

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

I can undestand what is problem because have some problem with reactJS

Looks like you are storing res.data.name instead of res.data . Meaning this.state.projects is getting set to a single name string. You should be setting this.state.projects to res.data to get the full array of projects:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM