[英]Problem in passing values using props in react.js while using chart.js
我正在使用 react js 並嘗試將道具從我的 app.js 發送到 chart.js 文件。 當我發送硬編碼值時,值被正確發送並根據它制作圖形。 但是每當我傳遞動態值時,都會傳遞值但圖表未使用這些值。
應用程序.js
class App extends React.Component {
state = {
text: "",
credit: [{_id:1,financeCredit:"loading"}],
debit: [{_id:1,financeDebit:"loading"}],
}
componentDidMount(){
fetch('/data')
.then(res=> res.json())
.then(res2 => {
console.log(res2)
this.setState({
credit: res2
})
})
fetch('/data2')
.then(res=> res.json())
.then(res2 => {
console.log(res2)
this.setState({
debit: res2
})
})
}
render(){
var lengthExpense = this.state.credit.length;
console.log(lengthExpense)
var expName = [];
for (var a = 0 ; a <= lengthExpense ; a++){
if (this.state.credit[a]){
expName.push(this.state.credit[a].expenseName)
}
}
var expAmount = [];
for (var b = 0 ; b <= lengthExpense ; b++){
if(this.state.credit[b])
expAmount.push(this.state.credit[b].expenseAmount)
}
console.log(expAmount)
console.log(expName)
return (
<BrowserRouter>
<div className="App">
<Navbar />
<Chart expam = {expAmount} expnam = {expName} />
<Route exact path = "/" component = {Home} />
</div>
</BrowserRouter>
);
}
}
export default App;
盡管以下 console.log() 顯示了我想傳遞的所需值
console.log(expAmount)
console.log(expName)
我像這樣傳遞這些值
<Chart expam = {expAmount} expnam = {expName} />
在chart.js 中,雖然我得到了這些值。
圖表.js
class Chart extends Component{
constructor(props){
super(props);
this.state = {
chartData : {
labels: this.props.expnam,
datasets: [{
label: 'Expense',
data: this.props.expam,
backgroundColor:'rgba(255, 99, 132, 0.6)'
}]
}
}
}
render(){
console.log(this.props)
return(
<div className = "chart">
<div>
<Bar id = "chart1"
data={this.state.chartData}
options={{ maintainAspectRatio: false, }}
/>
<canvas id = "chart1" height="30vw" width="10vw" ></canvas>
</div>
</div>
)
}
}
但無法將其傳遞給標簽和數據。 代碼正常運行但沒有值所以圖表顯示為空
constructor(props){
super(props);
this.state = {
chartData : {
labels: this.props.expnam,
datasets: [{
label: 'Expense',
data: this.props.expam,
backgroundColor:'rgba(255, 99, 132, 0.6)'
}]
}
}
}
在這個 chart.js 文件中,我可以看到從 App.js 傳遞的所有值。 但這些值並未用於圖表(條形圖)。
console.log(this.props)
似乎您正在構造函數中設置數據:
constructor(props){
super(props);
this.state = {
chartData : {...}
}
}
構造函數僅在對象初始化時調用一次。 (在 ReactJS 中,它僅在第一次渲染后調用。)
您正在調用setState()
,其余的似乎很好,我可以說。 為什么不將this.state = {...}
從構造函數移動到render()
? 由於render()
在狀態更改時運行,因此您的setState()
調用應該可以工作。
它可能不優雅,當然可以改進,但它會讓你朝着正確的方向開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.