我需要使这个函数可重用,但我不明白如何传递 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/