javascript - 如何在 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) 的结果是:
解决方案
我相信你可以做两件事之一来解决你的问题。
而不是 using
this.state.code
,为什么不简单地this.props.match.params.Code
在您的 axios 请求中使用呢?它未定义的原因是因为在您收到的构造函数中
props
,不是this.props
,所以您只需要将其更改为以下内容。
Code: props.match.params.Code
推荐阅读
- python - 我应该使用哪个 Python 库来让我将两个“大脑”群体相互竞争,作为确定健康度的一种手段?
- python - 将数字字符串列表转换为具有整数的元组 Python3
- php - 错误:创建或保存数据时试图获取非对象的属性
- fortran - 我可以使用 Fortran 创建一个没有变量赋值的数组吗?
- reactjs - 反应返回多个元素而不创建容器元素
- google-maps - 如何在没有标记的反应谷歌地图上显示模式?
- prolog - 我如何运行序言文件
- scenekit - 用户旋转场景/相机时如何不旋转 SCNSphere 中的环绕文本
- python - 如何修复小但相关的 Python 错误?
- ruby-on-rails - Rails autoload_paths 在 Rails 控制台中无法正常工作