Я перебираю содержимое следующего массива:
chosenBets: [
{
id: 2,
label: 2,
odd: 4.8,
team_home: "Liverpool",
team_away: "Sheffield United",
},
{
id: 2,
label: 2,
odd: 4.8,
team_home: "Liverpool",
team_away: "Sheffield United",
},
],
Чтобы получить общие коэффициенты каждой ставки:
const getTotalOdds = () => {
let totalOdds = 0
chosenBets.forEach(bet => {
totalOdds += bet.odd
})
let newState = Object.assign({}, state)
newState.totalOdds = totalOdds
setState({ ...newState })
}
Но когда я вызываю функцию внутри useEffect
это вызывает бесконечный цикл.
Полный код:
import * as React from "react"
import { Frame, Stack, addPropertyControls, ControlType } from "framer"
import { Input } from "./Input"
interface Bets {
id: number
label: number
odd: number
team_home: string
team_away: string
}
interface IProps {
chosenBets: Bets[]
}
const style = {
span: {
display: "block",
},
}
const Row = ({ label, property }) => (
<div style={{ display: "flex", width: "100%" }}>
<span style={{ ...style.span, marginRight: "auto" }}>{label}</span>
<span style={{ ...style.span }}>{property}</span>
</div>
)
export const BetCalculator: React.FC<IProps> = props => {
const { chosenBets } = props
const [state, setState] = React.useState({
stake: 10,
totalOdds: 0,
potentialPayout: 0,
})
const { stake, totalOdds } = state
const onChange = e => {
let newState = Object.assign({}, state)
newState.stake = Number(e.value)
setState({ ...newState })
}
const getTotalOdds = () => {
let totalOdds = 0
chosenBets.forEach(bet => {
totalOdds += bet.odd
})
let newState = Object.assign({}, state)
newState.totalOdds = totalOdds
setState({ ...newState })
}
const getPayout = () => {
let potentialPayout = totalOdds * stake
console.log(potentialPayout, "potentialPayout")
// let newState = Object.assign({}, state)
// newState.potentialPayout = potentialPayout
// setState({ ...newState })
}
React.useEffect(() => {
getTotalOdds()
getPayout()
}, [state])
return (
<Stack alignment="end" backgroundColor="white">
<Row
label="stake"
property={<Input onChange={onChange} value={stake} />}
/>
<Row label="Odds" property={totalOdds} />
</Stack>
)
}
BetCalculator.defaultProps = {
chosenBets: [
{
id: 2,
label: 2,
odd: 4.8,
team_home: "Liverpool",
team_away: "Sheffield United",
},
{
id: 2,
label: 2,
odd: 4.8,
team_home: "Liverpool",
team_away: "Sheffield United",
},
],
}
У меня следующие вопросы:
- Что вызывает это?
- Как мне решить?