【发布时间】:2019-03-05 10:51:16
【问题描述】:
我有一个反应原生组件。我得到了错误:
Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
代码:
import....
class Register extends Component {
static navigationOptions = {
header: null,
};
async handleSubmit(values, customerCreate) {
const { email, password, firstName, lastName, phone } = values;
const input = { email, password, firstName, lastName, phone };
const customerCreateRes = await customerCreate({ variables: { input } });
const isCustomerCreated = !!customerCreateRes.data.customerCreate.customer.id;
if (isCustomerCreated) {
const isStoredCrediential = await storeCredential(email, password);
if (isStoredCrediential === true) {
// Store in redux
// Go to another screen
console.log('test');
}
}
}
render() {
return (
<Mutation mutation={CREATE_CUSTOMER_ACCOUNT}>
{
(customerCreate, { error, data }) => {
return (
<MainLayout
title="Create Account"
backButton
currentTab="profile"
navigation={this.props.navigation}
>
{ showError }
{ showSuccess }
<RegistrationForm
onSubmit={async (values) => this.handleSubmit(values, customerCreate)}
initialValues={this.props.initialValues}
/>
</MainLayout>
);
}
}
</Mutation>
);
}
}
const mapStateToProps = (state) => {
return {
....
};
};
export default connect(mapStateToProps)(Register);
CREATE_CUSTOMER_ACCOUNT 是 graphql:
import gql from 'graphql-tag';
export const CREATE_CUSTOMER_ACCOUNT = gql`
mutation customerCreate($input: CustomerCreateInput!) {
customerCreate(input: $input) {
userErrors {
field
message
}
customer {
id
}
}
}
`;
谁在使用 handleSubmit?
表单中有一个按钮,按下时会调用handleSubmit。
这个语法正确 onPress={handleSubmit} 吗?
const PrimaryButton = ({ label, handleSubmit, disabled }) => {
let buttonStyle = styles.button;
if (!disabled) {
buttonStyle = { ...buttonStyle, ...styles.primaryButton };
}
return (
<Button block primary={!disabled} disabled={disabled} onPress={handleSubmit} style={buttonStyle}>
<Text style={styles.buttonText}>{label}</Text>
</Button>
);
};
导出默认PrimaryButton;
更新 1:
如果我删除customerCreate(来自graphql),错误就会消失。这意味着异步等待实际上是正确的,但我需要 customerCreate
【问题讨论】:
-
你能解释一下
customerCreate()方法是什么吗? -
@vuluu customerCreate 方法来自 CREATE_CUSTOMER_ACCOUNT,即 graphql。我相信/猜测客户创造回报的承诺。 (我已将其包含在我的问题中)
-
@kenpeter 一切看起来都很好。请检查
表单组件。他们可能有问题。 -
@Leu,请参阅上面的更新。够了吗?
-
你能删除
onSubmit={async (values) => this.handleSubmit(values, customerCreate)}行,看看是否可行,只是想确认一下,这是错误吗?
标签: reactjs react-native async-await graphql graphql-mutation