我正在遍历以下数组的内容:
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",
},
],
}
我的问题如下:
答案 0 :(得分:3)
const [stake, setStake] = useState(10);
const [totalOdds, setTotalOdds] = useState(0);
const [potentialPayout, setPotentialPayout] = useState(0);
易于管理。
useEffect
发生更改时都会调用您的state
,另一方面,每个useEffect
都会返回新的状态对象。无限循环。只需将计算结果放在onChange
函数中,就完全不需要useEffect
(或仅使用useEffect
会引起副作用,例如console.log
);