[英]How to get a data after react select using axios and ReactJS?
我是ReactJS的新手,我想在選擇產品名稱之后獲得一個Price值,然后選擇並顯示它。
我的方法:
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>
當我運行它時,價格列上沒有顯示任何內容,在我選擇產品名稱后,我得到:
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)
我該如何閱讀和顯示它?
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
編輯
我可以看到你能夠得到響應,但反應仍然給出錯誤: - 將paragrah代碼更改為
<p>{this.state.PrixV[0].PrixV} </p>
或者好的方法是正確設置數據,所以讓paragrah相同
<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作為數組(對象)而非原始數據類型。 希望這能解決問題。
您必須使用地圖,嘗試更改代碼,如下所示:
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);
});
}
我希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.