我需要使该函数可重用,但我不明白如何将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上返回新状态
答案 0 :(得分:1)
我会将此函数设为纯函数,并在需要生成这些随机名称时使用它,例如
class SomeComponent extends Component {
handleClick = () => {
const {random, randomOptions} = getRandomEmployee()
this.setState({
randomOptions,
random,
})
}
}
答案 1 :(得分:0)
我在这里注意到了几件事:
1)您有一些重复的代码-> filteredEmployee[Math.floor(Math.random() * filteredEmployee.length)]
最好将其抽象出来。您可以这样做:
function getRandomIndex(dataArray) => dataArray[Math.floor(Math.random() * dataArray.length)]
然后,您可以像这样调用函数:const randomOption = this.getRandomIndex(filteredEmployee)
2)要使setState起作用,取决于您的此方法位于何处。是在处理状态的组件内部吗?如果不是,一种选择是让您的getRandomEmployee
简单地返回您需要的对象,并使组件调用setState。