重定向在 Accounts.createUser() 中不起作用
Redirect is not working in the Accounts.createUser()
我在 meteorJS 中使用了 react-router-dom。创建帐户后,我尝试重定向。现在帐户已成功创建,但重定向不起作用。
我也试过在账号创建成功后添加setState。它也不起作用。
handleSubmit(event) {
event.preventDefault();
Accounts.createUser(
{
username: this.state.mobile,
password: "123"
},
function(err) {
if (err) {
console.log("err", err);
} else {
console.log("account created");
this.setState({
redirect: true
});
return <Redirect to="/" />;
}
}
);
}
此消息显示在控制台中
Exception in delivering result of invoking 'createUser': TypeError: this.setState is not a function
您需要将回调绑定到您当前的上下文,您可以使用箭头函数来完成。
此外,回调中的 return 语句没有按照您的想法执行,该值已丢失,您应该使用历史对象推送新路由
handleSubmit(event) {
event.preventDefault();
Accounts.createUser(
{
username: this.state.mobile,
password: "123"
},
err => { // here use the arrow function to bind to the current "this"
if (err) {
console.log("err", err);
} else {
console.log("account created");
this.setState({
redirect: true
});
hashHistory.push("/"); // push the next route
}
});
}
你失去了背景
handleSubmit(event) {
event.preventDefault();
let that = this;
Accounts.createUser(
{
username: this.state.mobile,
password: "123"
},
function(err) {
if (err) {
console.log("err", err);
} else {
console.log("account created");
that.setState({
redirect: true
});
return <Redirect to="/" />;
}
}
);
}
我在 meteorJS 中使用了 react-router-dom。创建帐户后,我尝试重定向。现在帐户已成功创建,但重定向不起作用。
我也试过在账号创建成功后添加setState。它也不起作用。
handleSubmit(event) {
event.preventDefault();
Accounts.createUser(
{
username: this.state.mobile,
password: "123"
},
function(err) {
if (err) {
console.log("err", err);
} else {
console.log("account created");
this.setState({
redirect: true
});
return <Redirect to="/" />;
}
}
);
}
此消息显示在控制台中
Exception in delivering result of invoking 'createUser': TypeError: this.setState is not a function
您需要将回调绑定到您当前的上下文,您可以使用箭头函数来完成。
此外,回调中的 return 语句没有按照您的想法执行,该值已丢失,您应该使用历史对象推送新路由
handleSubmit(event) {
event.preventDefault();
Accounts.createUser(
{
username: this.state.mobile,
password: "123"
},
err => { // here use the arrow function to bind to the current "this"
if (err) {
console.log("err", err);
} else {
console.log("account created");
this.setState({
redirect: true
});
hashHistory.push("/"); // push the next route
}
});
}
你失去了背景
handleSubmit(event) {
event.preventDefault();
let that = this;
Accounts.createUser(
{
username: this.state.mobile,
password: "123"
},
function(err) {
if (err) {
console.log("err", err);
} else {
console.log("account created");
that.setState({
redirect: true
});
return <Redirect to="/" />;
}
}
);
}