这不起作用,因为 Partial<IState>
返回一个可以有 undefined
的类型s 作为 setState
不接受的值.
interface IState {
bar: number
baz: boolean
}
class App extends React.Component<{}, IState> {
constructor(props) {
super(props)
this.state = {
bar: 123,
baz: false,
}
}
public render() {
return null
}
public update(options: Partial<IState>) {
this.setState(options)
}
public callUpdate() {
this.update({ bar: 4 })
}
}
我找到的唯一解决方案是将当前状态也添加到 setState 中:
this.setState({ ...this.state, ...options })
有没有更好的方法来做到这一点?
typescript 版本:3.2.1
最佳答案
您可能想要使用类型断言:
this.setState(options as IState)
不推荐使用 this.setState({ ...this.state, ...options })
因为你必须解构当前状态对象,这是不必要的
关于reactjs - 如何为使用参数调用 React setState 的函数创建 TypeScript 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53584442/