我正在使用React中的流进行类型检查。我在以下情况下遇到错误,如何处理this.props.history.push('/ home')如何在道具中定义它?我已经尝试过下面的方法,但是它不起作用,
type Prop = { onLoginSuccess: function, setContextDetails: function, callErrorLogger: function, history:string, push:string };
type State = { username: string, password: string, loginsuccess: bool, isLoading: bool };
class Login extends React.Component<Prop, State> {
// here I have some code
this.props.history.push('/home') ;
}
我清理了您的一些代码和类型,以针对流语法更正确。但这应该可行。
您基本上以与普通对象相同的方式定义history
类型,并且push
函数可以用Function
声明,也可以使用我下面使用的箭头函数语法更严格地声明。
type Prop = {
onLoginSuccess: Function,
setContextDetails: Function,
callErrorLogger: Function,
history: {
push: (string) => void,
},
};
type State = {
username: string,
password: string,
loginsuccess: boolean,
isLoading: boolean,
};
class Login extends React.Component<Prop, State> {
// here I have some code
onClick() {
this.props.history.push('/home');
}
}
[我也建议以后将您的帖子标记为flowtype
,这会获得更多帮助。