如何在React中使用道具工作参数?

时间:2018-07-18 18:46:07

标签: javascript reactjs parameters react-props react-proptypes

我是新开发人员 ReactJS ,我使用前端的 ReactJS ,后端的 NodeJS MySQL 开发了一个表关于数据库的strong>。

当我单击“操作”列上的查看按钮时,我想要如下所示: enter image description here

我的路由器:

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);
    });

}

我的服务器:

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

我在Liste类上的 handleView 方法:

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


    };
handleView(Code) {
    try {

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

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

查看课程:

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


            };
console.log(this.props);
     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的结果。

console.log(this.props)的结果是:

enter image description here 我该如何解决?

1 个答案:

答案 0 :(得分:1)

我相信您可以做以下两件事之一来解决您的问题。

  1. 为什么不直接在您的axios请求中使用this.state.code,而不使用this.props.match.params.Code

  2. 之所以未定义,是因为在构造函数中您收到props,而不是this.props, 因此您只需要将其更改为以下内容即可。

Code: props.match.params.Code