我正在构建一个小型的React应用程序,该应用程序可以处理并在单击按钮时重新渲染一些不同的状态对象。对于其中两个(股票,帐户),它们可以使用setState函数很好地渲染,但是对于gameplayHandler()中的项目,它们可以渲染到控制台,但不能渲染到浏览器。他们并不需要像其他两个组件那样严格地使用自己的组件。
我认为我正在做一些很明显的错误-谁能给我一个有关如何获取以下所有渲染的提示?
谢谢。
import React, { Component } from 'react'
import './App.css'
import {stocks, accounts, gameplay} from './dummy_data/data'
import Stock from './Stock/Stock'
import Account from './Account/Account'
class App extends Component {
state = {
stocks: stocks,
accounts: accounts,
gameplay: gameplay
}
sleep = () => {
this.stockHandler()
this.accountHandler()
this.gameplayHandler()
}
gameplayHandler = () => {
let netWorth = this.state.accounts.reduce(function(prevAcc,curAcc){
return prevAcc + curAcc.balance
},
0)
this.setState({
gameplay: [
{
playerName: gameplay.playerName,
gameDay: gameplay.gameDay += 1,
netWorth: netWorth.toFixed(2)
}
]
})
}
accountHandler = () => {
this.state.accounts.map(newAccount => {
const interestPayment = parseFloat(((newAccount.balance / 100) * newAccount.interestRate).toFixed(2))
newAccount.balance = Math.round((newAccount.balance + interestPayment) * 100) / 100
})
return this.setState({
accounts: accounts
})
}
stockHandler = () => {
this.state.stocks.map(newStock => {
newStock.currentPrice *=2
})
this.setState({
stocks: stocks,
})
}
render() {
let accounts = null
if (this.state.accounts) {
accounts = (
<div>
{this.state.accounts.map(account => {
return <Account key={account.key} name={account.name} balance={account.balance}/>
})}
</div>
)
}
let stocks = null
if (this.state.stocks) {
stocks = (
<div>
{this.state.stocks.map(stock => {
return <Stock key={stock.key} name={stock.name} currentPrice={stock.currentPrice}/>
})}
</div>
)
return (
<div className="App">
> Gameplay:
<div>Player Name: {this.state.gameplay.playerName}, Game Day: {this.state.gameplay.gameDay}, Job Title: {this.state.gameplay.jobTitle}, Net Worth: £{this.state.gameplay.netWorth}</div>
> Stocks:
{ stocks }
> Accounts:
{ accounts }
<button onClick={this.sleep}>Go =></button>
</div>
)
}
}
}
导出默认应用
答案 0 :(得分:0)
这很奇怪,因为首先需要绑定gameplayHandler
函数。因此应该像这样:
constructor(props) {
super(props);
this.state = {
stocks: stocks,
accounts: accounts,
gameplay: gameplay
};
this.gameplayHandler = this.gameplayHandler.bind(this);
}
否则,当您尝试使用setState
时,它应该会给出一个错误,当然您应该绑定accountHandler
和stockHandler
函数。即使绑定这些功能,您能否告诉我问题仍然存在?