gpt4 book ai didi

javascript - 重构以使函数可通过 setState 重用

转载 作者:行者123 更新时间:2023-12-03 00:16:45 25 4
gpt4 key购买 nike

我需要使这个函数可重用,但我不明白如何传递 setState 使其在其中可用

function getRandomEmployee(updateStateFn){
const filteredEmployee = employeeList.filter(image => image.hasImage === true)
const random = filteredEmployee[Math.floor(Math.random() * filteredEmployee.length)]
const randomOpt1 = filteredEmployee[Math.floor(Math.random() * filteredEmployee.length)]
const randomOpt2 = filteredEmployee[Math.floor(Math.random() * filteredEmployee.length)]
const randomOpt3 = filteredEmployee[Math.floor(Math.random() * filteredEmployee.length)]
const randomOptions = [random.fullName, randomOpt1.fullName, randomOpt2.fullName, randomOpt3.fullName]
randomOptions.sort(() => { return 0.5 - Math.random() })
setState(state => {
const newState = updateStateFn && updateStateFn(state)
return {...newState, randomEmployee: random, randomOptions: randomOptions, playerIsWin:'', disableFieldset: false}
})
}

我希望该函数输出随机 4 个名称并在 setState 上返回新状态

最佳答案

我会让这个函数变得纯粹,并在您需要生成这些随机名称时使用它,例如

class SomeComponent extends Component {
handleClick = () => {
const {random, randomOptions} = getRandomEmployee()
this.setState({
randomOptions,
random,
})
}
}

关于javascript - 重构以使函数可通过 setState 重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54502711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com