javascript - 类型错误 : Cannot read property 'then' of undefined in react js

标签 javascript reactjs

这是我的 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/

相关文章:

c# - 使用选择更改淡出或淡入另一个字段

javascript - React中如何淡出和淡入?

javascript - Uncaught Error : 'node' must be a RefObject when passing a React. RefObject

reactjs - Electron react 样板 :sub window on clicking a button

node.js - Next.js 服务器端 api 调用返回 500 内部服务器错误

javascript - 在全屏覆盖中打印文本?

javascript - 重复的 JavaScript 输出

javascript - 访问 td with class on row open

javascript - iframe 404错误

javascript - 传递 props 时我应该总是写 this.props 吗?