【发布时间】:2019-08-13 12:06:54
【问题描述】:
我有以下子组件:
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 函数之外使用处理程序来启动具有正确变量值的突变请求?我也很想知道为什么这个构造不起作用并且变量是空的。
【问题讨论】:
-
你可以试试
let { email, password }而不是const { email, password } -
@ViswanathLekshmanan:是一样的。
-
<SignIn onClick={(e, p) => this.handleClick(e, p, request)} />;中的e和p是什么? -
@ViswanathLekshmanan 它是来自 SignIn 组件的电子邮件和密码,通过
handleClick处理程序,结合request对象用于发起请求。 -
可以发
request()的方法吗
标签: javascript react-apollo apollo-client