【发布时间】:2019-05-09 01:21:26
【问题描述】:
我正在尝试通过 axios 从 REST 端点获取数据,然后在我的 app.js 组件中呈现它们,然后使用上下文 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>
);
}
第一个问题是,当我尝试渲染它时,它显示了我的“日志”属性,尽管我记录并测试了它并且工作正常,它显示此错误:“无法读取属性'日志'未定义”
第二个问题是,当我删除具有此属性的 CustomTableCell 时,它会将我的数据加载到表外,并为我提供表外的整个对象数组。
因此,任何帮助都将在这里得到赞赏。
【问题讨论】:
-
分享第一期的错误信息。
标签: reactjs axios material-ui