我有以下子组件:
class SignIn extends React.Component {
constructor(props) {
super(props);
this.onClick = this.handleClick.bind(this);
this.state = {
email: '',
password: ''
};
}
handleClick = () => {
this.props.onClick(this.state.email, this.state.password);
}
handleEmailChange = (e) => {
this.setState({email: e.target.value});
}
handlePasswordChange = (e) => {
this.setState({password: e.target.value});
}
render() {
return (
...
<Input id="email" name="email" autoComplete="email" autoFocus
value={this.state.email} onChange={this.handleEmailChange}/>
<Input name="password" type="password" id="password" autoComplete="current-password"
value={this.state.password} onChange={this.handlePasswordChange}/>
...
);
}
}
现在从父母那里我有以下组成部分:
class App extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
email: "",
password: ""
}
}
handleClick(e, p, request) {
request();
}
render() {
const { email, password } = this.state;
console.log('render', email, password); // here I see the right state after click
return (
<ApolloProvider client={client}>
<Mutation mutation={LOGIN} variables={{ email: email, password: password }} onError={() => {}}>
{(request, result) => {
const { data, loading, error, called } = result;
if(!called) {
return <SignIn onClick={(e, p) => this.handleClick(e, p, request)} />;
}
if(error) {
return <div>Error</div>;
}
if(loading) {
return <div>Loading...</div>;
}
...
return <div>Mutation processed</div>;
}}
</Mutation>
</ApolloProvider>
);
}
}
我要实现的是单击按钮后的单独处理程序,并在某些逻辑后启动突变发送。但是,通过这种方式,变量(电子邮件,密码)总是空发送到网络。如果我将request
直接放在句柄中,那么它将起作用。
如何在render
函数之外使用处理程序来启动具有正确变量值的变异请求?我也非常想知道为什么这种构造不起作用并且变量为空。
答案 0 :(得分:0)
我认为问题出在这里:
newData = std::move(oldData); // move assignment
使用错误的绑定,您将不会触发所需的方法。 应该为:
this.onClick = this.handleClick.bind(this);
以下内容实现了您想要的。我已经精简了一下,因为我对您的Apollo实现一无所知,但希望您能掌握要点:
this.handleClick = this.handleClick.bind(this);