【问题标题】:How to display the result of Select query on list with ReactJS?如何使用 ReactJS 在列表上显示 Select 查询的结果?
【发布时间】:2018-07-19 13:30:53
【问题描述】:

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

我希望当我点击 Action 列上的查看按钮时,它将被重定向到另一个页面,该页面显示一个包含 Select 查询结果的列表,如下所示:

ViewCLient.js:

class ViewClient extends Component {
    constructor(props) {
        super(props);
        this.state = {
            clients: [],
            Code :1111
        };
        this.toggle = this.toggle.bind(this);
        this.state = {
            activeTab: '1',
        };
    }

    toggle(tab) {
        if (this.state.activeTab !== tab) {
            this.setState({
                activeTab: tab,
            });
        }
    }
    componentDidMount(Code) {
        
        axios({
                method: "get",
                url: "/app/viewclient/"+Code  ,
                withCredentials: true,
                headers: {
                    "Access-Control-Allow-Origin": "*",
                    "Content-Type": "application/json",
                    Accept: "application/json"
                }
            })
            .then(response => {
                if (response && response.data) {
                    this.setState({ clients: response.data });
                }
            })
            .catch(error => console.log(error));
    }

    render() {
        let { clients } = this.state;
       // let { clients } = this.state;
        return (
            <div className="animated fadeIn">
        <Row>
         
           <Col xs="12" md="6" className="mb-4">
            <Nav tabs>
              <NavItem>
                <NavLink
                  className={classnames({ active: this.state.activeTab === '1' })}
                  onClick={() => { this.toggle('1'); }}
                >
                  <i className="fa fa-info"></i> <span className={this.state.activeTab === '1' ? '' : 'd-none'}> Détails</span>
                </NavLink>
              </NavItem>
              <NavItem>
                <NavLink
                  className={classnames({ active: this.state.activeTab === '2' })}
                  onClick={() => { this.toggle('2'); }}
                >
                  <i className="fa fa-credit-card"></i> <span
                  className={this.state.activeTab === '2' ? '' : 'd-none'}> Factures</span>
                </NavLink>
              </NavItem>
              <NavItem>
                <NavLink
                  className={classnames({ active: this.state.activeTab === '3' })}
                  onClick={() => { this.toggle('3'); }}
                >
                  <i className="fa fa-truck"></i> <span className={this.state.activeTab === '3' ? '' : 'd-none'}> Bons de livraison</span>
                </NavLink>
              </NavItem>
            </Nav>
            <TabContent activeTab={this.state.activeTab} style={{ height:"420px"}}>
              <TabPane tabId="1">
               <ul>
               {
                       clients &&  clients.map(client => (
                            <li key={client.Code}>
                         <h1> Code client :    {client.Code} </h1>
                             {client.Prenom}
                              {client.Nom}
                              {client.FAX}
                             {client.Telephone}
                               {client.Email}
                                {client.Adresse1}
                                 {client.Adresse2}
               </li>
               ))}
               </ul>
              </TabPane>
              <TabPane tabId="2">
                
              </TabPane>
              <TabPane tabId="3">
              
              </TabPane>
            </TabContent>
          </Col>
          
        </Row>
      </div>
        );
    }
}

export default ViewClient;

ListClient.js

class ListeClients extends Component {


  constructor(props) {
    super(props);
    this.state = {
      clients: []
    };
    this.handleView = this.handleView.bind(this);
    this.handleEdit = this.handleEdit.bind(this);
  }

  componentDidMount() {
    axios({
        method: "get",
        url: "/app/listeclients/",
        withCredentials: true,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Content-Type": "application/json",
          Accept: "application/json"
        }
      })
      .then(response => {
        if (response && response.data) {
          this.setState({ clients: response.data });
        }
      })
      .catch(error => console.log(error));
  }

/*handleViewB(Code) {
   this.props.history.push('/clients/viewclient/');
}*/
handleView( evt) {
    try {
      console.log("Voir client")
      this.props.history.push('/clients/viewclient/');
      // Do something that could throw
    }
    catch (error) {
      this.setState({ error });
    }
  }
  handleEdit(event) {
    try {
    console.log("Modifier client")
    this.props.history.push('/clients/editclient/');
    // Do something that could throw
     } catch (error) {
       this.setState({ error });
     }
  }
  // event.preventDefault;





  render() {
    let { clients } = this.state;
     let Code = this.state;
    var btn = {
      backgroundColor: 'Transparent',
      backgroundRepeat: 'no-repeat',
      border: 'none',
      cursor: 'pointer',
      overflow: 'hidden',
      outline: 'none'
    }
    var center = {
      textAlign: "center"
    }
    return (
      <div className="animated fadeIn">
       
          
            <Card style={{ height:"420px"}}>
              <CardHeader>
                <h4>
                  <strong>
                    <i className="fa fa-align-justify" /> Tous les clients
                  </strong>
                </h4>
              </CardHeader>
              <CardBody>
              
                    <Table  bordered responsive size="sm" style={center}>
                      <thead >
                        <tr>
                          <th ><strong>Code</strong></th>
                          <th>Prenom</th>
                          <th>Nom</th>
                          <th>Email</th>
                          <th>Telephone</th>
                          <th>Action</th>
                        </tr>
                      </thead>
                      <tbody>
                        {
                          clients.map(client => (
                            <tr key={client.Code}>
                              <td>{client.Code} </td>
                              <td>{client.Prenom}</td>
                              <td>{client.Nom}</td>
                              <td>{client.Email}</td>
                              <td>{client.Telephone}</td>
                              <td>
                                <button style={btn}   onClick={this.handleView} type="button"><i class="fa fa-eye"></i></button>
                                <button style={btn} onClick={this.handleEdit} type="button"><i class="fa fa-edit"></i></button>
                                <button style={btn}><i class="fa fa-trash-o"></i></button>
                              </td>
                            </tr>
                          ))}
                      </tbody>
                    </Table>
              
              </CardBody>
            </Card>
         
        
         
      </div>
    );
  }
}

export default ListeClients;

我的 router.js :

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

}

我的 server.js :

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

当我运行后端时,它可以很好地与 Postman 一起运行,但是当我使用 ReactJS 运行它时,它会将我重定向到 http://localhost:3000/app/viewclient/,但没有显示任何内容并且路由器控制台console.log(req.params)返回{ Code: 'undefined' }

请问如何解决?

【问题讨论】:

  • 您的 React 组件从 '/app/viewclient/' 获取,解析为 http://localhost:300/app/viewclient/。您需要将完整的 url 传递给 axios。
  • 哪个url,一定要传?
  • 查看@madhu-bhat 的答案
  • @Christophe 问题在于前端使用的 url,在 ViewClients.js 上的 axios 上或在 ListeClients.js 上的 handleView
  • 你试过用url: "http://localhost:4000/app/viewclient/"替换url: "/app/viewclient/"+Code吗?

标签: javascript mysql node.js reactjs axios


【解决方案1】:

默认情况下,React 应用程序会尝试连接到端口 3000 上的 url。因此,您需要向 axios 提供带有服务器运行端口号的完整 url(您在 Postman 上尝试的 url),或者修改 package.jsonscripts 属性以包含服务器端口号。

另外,在 ViewClient.js 中实现 componentDidMount 的方式不正确。在componentDidMount(Code) 中,Code 将是未定义的。如果Code 的值是常量,您可以使用状态访问componentDidMount 中的值。所以改成下面这样:

 componentDidMount() {

    axios({
            method: "get",
            url: "/app/viewclient/"+this.state.Code  ,
            withCredentials: true,
            headers: {
                "Access-Control-Allow-Origin": "*",
                "Content-Type": "application/json",
                Accept: "application/json"
            }
        })
        .then(response => {
            if (response && response.data) {
                this.setState({ clients: response.data });
            }
        })
        .catch(error => console.log(error));
}

【讨论】:

  • 我的前端和后端都有"proxy": "http://localhost:4000/",我有app.use(function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000/'); 我认为问题在于前端使用的网址,即axios 上的ViewClients.jshandleView ListeClients.js
  • http://localhost:4000/app/viewclient/1111 返回[{"Code":1111,"Prenom":"test","Nom":"test","FAX":"58985688888","Telephone":"58985699888","Email":"test@gmail.com","Adresse1":"","Adresse2":""}]
  • 看起来您设置的代理不起作用,因此它会将您重定向到端口 3000 而不是 4000。您在哪个文件中添加了代理,您可以共享相同的吗?跨度>
  • 我在文件package.json上添加了代理"proxy": "http://localhost:4000/"
  • 抱歉没有找到你@CodeLover。你的问题没有解决吗?你刚才说它有效。
猜你喜欢
  • 2018-05-11
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
相关资源
最近更新 更多