Can't display data after fetch

柔情痞子 提交于 2021-01-29 09:20:30

问题


I'm trying to get a data from an REST endpoint through axios and then render them in my app.js component and after that provide them to the whole app by using context API:

axios.js

import axios from 'axios';

const instance = axios.create({
    baseURL: 'api_endpoint'
});


export default instance;

app.js

import Context from './context'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      comp: []
    }
  };
async componentDidMount() {
     await instance.get('')
      .then(res => {
          const data = JSON.stringify(res.data.data)
          this.setState({comp: data});
          console.table('componentDidMount', data); // here I can log the data
      })
      .catch(err => {
        console.log(err)
      });

  }

 render () {
    return (

      <Context.Provider 
        value={{
          comp: this.state.comp
        }}>
      </comp.Provider>

    );
  }
}

export default App;

children.js

import Context from '../../context'

class Children extends Component { 
    render () {
        const { classes } = this.props;
        return (
          <Context.Consumer>
                    {context => (
                  <Paper className={classes.root}>
                    <Table className={classes.table}>
                      <TableHead>
                        <TableRow>
                          <CustomTableCell>comp_id</CustomTableCell>
                          <CustomTableCell align="right">comp_name</CustomTableCell>
                          <CustomTableCell align="right">comp_price</CustomTableCell>
                          <CustomTableCell align="right">comp_log_usd</CustomTableCell>
                        </TableRow>
                      </TableHead>

                      <TableBody>
                        {Object.entries(context.comp).forEach(([key, value]) => (
                          <TableRow className={classes.row} key={value.id}>
                          <CustomTableCell component="th" scope="row">
                            {value.id}
                          </CustomTableCell>
                          <CustomTableCell align="right">{value.name}</CustomTableCell>
                          <CustomTableCell align="right">{value.price}</CustomTableCell>
                          <CustomTableCell align="right">{value.log.usd}</CustomTableCell>
                        </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </Paper>
              )}
            </Context.Consumer>
        );
    }

The first problem is that when I try to render it like that it shows that my "log" property despite that I logged it and tested it and it works fine, it shows this error: "Cannot read property 'log' of undefined"

second issue is that when I remove CustomTableCell which have this property then it loads my data outside of the table and it gives me the whole array of objects outside of my table.

So, any help will be appreciated here.


回答1:


If your going to use async functions then don't use .then() it makes it too hard to track in my opinion. I have never used async on component did mount and this answer assumes that that's fine but try this

 async componentDidMount() {
  try{
   let response = await instance.get('')
   const data = JSON.stringify(response.data.data)
   this.setState({comp: data});
   console.table('componentDidMount', data); // here I can log the data
  }
  catch(error){console.log(error);
 }


来源:https://stackoverflow.com/questions/56050951/cant-display-data-after-fetch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!