Axios获取请求问题

时间:2018-07-18 10:54:19

标签: javascript mysql node.js reactjs axios

当我单击下面“操作”列上的查看按钮时,我想要

enter image description here

它将重定向到另一个页面,该页面显示包含Select查询结果的列表。代码如下:

我的路由器:

exports.viewclient = function(req, res) {
  var Code = req.query.Code;
    console.log(req.params);

    connection.query('SELECT Code, Prenom, Nom, FAX, Telephone, Email, Adresse1, Adresse2  FROM clients  WHERE Code = ?',[req.params.Code],  function(error, results, fields) {
        if (error) throw error;
        res.send(JSON.stringify(results));
console.log(results);
    });

}

我的服务器:

router.get('/viewclient/:Code', clients.viewclient);

我在Liste类上的handleView方法:

handleView(event) {
    try {

      console.log("Voir client")
      this.props.history.push('/clients/viewclient/' + this.state.Code);

    }
    catch (error) {
      this.setState({ error });
    }
  }

查看课程:

constructor(props) {
        super(props);
        this.state = {
            clients: [],
            Code: this.props.match.params.Code


        };
 componentDidMount() {


    axios.get('http://localhost:4000/app/viewclient/' + this.state._code)

        .then(response => {
            if (response && response.data) {
                this.setState({ clients: response.data });
            }
        })
        .catch(error => console.log(error));
}

当我使用Postman http://localhost:4000/app/viewclient/1111运行后端时,它返回[{"Code":1111,"Prenom":"test","Nom":"test","FAX":"58985688888","Telephone":"58985699888","Email":"test@gmail.com","Adresse1":"","Adresse2":""}]

但是当我运行前端时,它会将我重定向到http://localhost:3000/app/viewclient/undefined,但是我无法查看Select的结果。

我该如何解决?

2 个答案:

答案 0 :(得分:2)

您的状态如下:

this.state = {
  clients: [],
  Code: this.props.match.params.Code
};

但是你这样称呼你的状态

this.state._code

状态变量的名称必须相同,因此请更改状态变量或调用以使其匹配:

this.state = {
  clients: [],
  Code: this.props.match.params.Code
};

axios.get('http://localhost:4000/app/viewclient/' + this.state.Code)

答案 1 :(得分:2)

在课堂视图中,我编辑:

constructor(props) {
        super(props);
        this.state = {
            clients: [],
            Code: props.match.params.Code
        };
componentDidMount() {
        axios.get('http://localhost:4000/app/viewclient/' + this.props.match.params.Code).then(function(response) {
            if (response.status >= 400) {
                throw new Error("Bad response from server");
            }
            return response.json();
        }).then(function(data) {
            if (data === "success") {
                this.setState({ msg: "User has been deleted." });
            }
        }).catch(function(err) {
            console.log(err)
        });
    }

这使其运作良好。