重构使一个可重复使用的功能用的setState

问题描述 投票:0回答:2

我需要这个功能,可重复使用的,但我不明白怎么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新国家

javascript reactjs
2个回答
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。


1
投票

我会做这个功能纯粹,当你需要生成这些随机的名字使用它,例如

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

© www.soinside.com 2019 - 2024. All rights reserved.