这是我的 Main.js 文件
import React from 'react';
import axios from 'axios';
const editByID = (id) =>{
axios.post('http://localhost:8000/getbyID',{
id:id
})
.then(({data}) => {
if(data.success == 1){
alert(data.msg);
let tmpArr = [];
for( var i = 0 ; i < data.user.length ; i++ ){
tmpArr.push(data.user[i])
}
// uid = data.user[0].id;
return tmpArr
// console.log(data.user[0].id);
// editUser(uid);
}
else{
alert(data.msg);
}
})
.catch(error => {
console.log(error);
});
} //editByID
export default HomePage;
export {getData,editByID};
这是我的 FormUpdate.js 文件
componentDidMount(){
this.getAllByID();
}
getAllByID = () =>{
editByID().then(tmpArr=>{
this.setState({
items:tmpArr
},
()=>{
console.log(this.state);
})
})
} //getAllByID
在 FormUpdate.js 中,tmpArr 没有作为数组获取。但为什么?它显示以下错误:
TypeError: Cannot read property 'then' of undefined
FormUpdate.getAllByID
F:/react/react-crud/src/components/FormUpdate.js:21
18 |
19 | getAllByID = () =>{
20 | console.log(this.props.location.id);
> 21 | editByID(this.props.location.id).then(tmpArr=>{
| ^ 22 |
23 | this.setState({
24 | items:tmpArr
我做错了什么?当我从 Main.js 执行 console.log(tmpArr) 时,它完美地显示了结果。
最佳答案
editById
不返回任何内容。添加 return
关键字:
const editByID = (id) => {
return axios.post('http://localhost:8000/getbyID',{ // Add return here
id:id
})
...(rest of code)...
关于javascript - 类型错误 : Cannot read property 'then' of undefined in react js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60986778/