我是新手在ReactJS上,我想获得一个价格值后,通过反应选择并显示它的产品名称的选择。
我的方法是:
constructor(props) {
super(props);
this.state = {
PrixV: ""
}
PrixDisplay(selectprdt) {
return axios.get("/app/getPrixprod/" + selectprdt).then(response => {
if (response && response.data) {
this.setState({
PrixV: response.data
});
}
console.log(response.data)
}).catch(error => {
console.error(error);
});
}
我尝试通过以下方式读取此值:
<p>{this.state.PrixV} </p>
当我运行它时,在Price列上没有显示任何内容,并且在我选择产品名称后,我得到:
Objects are not valid as a React child (found: object with keys {PrixV}). If you meant to render a collection of children, use an array instead.
in p (at AjouterFacture.js:383)
然后控制台返回:
[{…}]0: {PrixV: "250.000"}length: 1__proto__: Array(0)
如何读取和显示它?
发布于 2018-08-18 19:40:58
您必须使用地图,尝试像这样更改代码:
constructor(props) {
super(props);
this.state = {
Prix: []};
render() {
let {
Prix
} = this.state.Prix;
return (
<td>
{ this.state.Prix.map((pr, k) =>
<p key={k} >{pr.PrixV} </p>
)}
</td>
);}
PrixDisplay(selectprdt) {
return axios.get("/app/getPrixprod/" + selectprdt).then(response => {
if (response && response.data) {
this.setState({
Prix: response.data
});
}
}).catch(error => {
console.error(error);
});
}
我希望这会对你有所帮助。
发布于 2018-08-18 04:28:04
constructor(props) {
super(props);
this.state = {
mydata: ''
};
productNameSelected(selectprdt) {//not sure from where you will get selectprdt variable , but something like this will work
axios.get("/app/getPrixprod/" + selectprdt).then(response => {
if (response && response.data) {
this.setState( {mydata : response.data});
}
console.log(response.data)
})
}
<p>{this.state.mydata} </p> //my data should not be a object , so you need to make string if you wnat to directly use it here
编辑
我可以看到你可以得到响应,但是react仍然给出错误:--将code代码更改为
<p>{this.state.PrixV[0].PrixV} </p>
或者,最好的方法是正确地设置数据,这样就可以使用相同的数据。
<p>{this.state.PrixV} </p>
PrixDisplay(selectprdt) {
return axios.get("/app/getPrixprod/" + selectprdt).then(response => {
if (response && response.data && response.data[0]) {
this.setState({
PrixV: response.data[0].PrixV
});
}
console.log(response.data)
}).catch(error => {
console.error(error);
});
}
您得到的错误是因为您当前将PrixV作为数组(对象)而不是原始数据类型获取。希望这能解决这个问题。
https://stackoverflow.com/questions/51902306
复制相似问题