首页 > 解决方案 > 如何在 React 中使用 props 处理参数?

问题描述

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

当我单击操作列上的查看按钮时,我想要如下所示: 在此处输入图像描述

我的路由器:

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方法:

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) 的结果是:

在此处输入图像描述 请问我该如何解决?

标签: javascriptreactjsparametersreact-propsreact-proptypes

解决方案


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

  1. 而不是 using this.state.code,为什么不简单地this.props.match.params.Code在您的 axios 请求中使用呢?

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

Code: props.match.params.Code


推荐阅读