我在将数据传递给 map 函数时遇到了一些麻烦,我不确定我哪里出错了。
当组件安装时我得到了所有用户,但是在我得到用户之后我试图添加一个常量。这一切都有效,但是在构造函数中,当我尝试映射数组时,它似乎没有找到它。
class UserManagement extends Component {
fetchUsers() {
axios.get('http://apiyall.com/users')
.then(res => {
const dataTable = res.data;
})
.catch(err => console.log(err));
}
componentDidMount() {
this.fetchUsers();
}
constructor(props) {
super(props);
this.state = {
data: dataTable.map((prop, key) => {
构造函数在组件生命周期中的 componentDidMount 之前只执行一次。在构造函数中,您可以初始化状态并绑定函数。如果你想用 'map' 函数迭代数组,你应该从 props 接收数据。
您应该按如下方式更改代码:
constructor(props) {
super(props);
this.state = {
data: []
}
}
componentDidMount() {
this.fetchUsers();
}
fetchUsers() {
axios.get('http://apiyall.com/users')
.then(res => {
this.setState({data: res.data}) //set the state here.
})
.catch(err => console.log(err));
}
render() {
this.state.data.map(() => {...});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句