【发布时间】:2019-02-21 11:17:28
【问题描述】:
我有一个包含用户验证表单的组件。该组件在挂载时运行 graphql 查询。在验证组件中,我需要使用来自 graphql 查询的数据来设置状态,以便我可以使用它来更新任何值,然后将它们与表单一起提交。从那以后,我了解了getDerivedStateFromProps,并且正在努力从该数据中填充一个新状态。但是,数据在 DOM 中不可用。就好像在 getDerivedStateFromProps 之前调用了 render。
这是组件:
class Verification extends React.Component {
constructor(props) {
super(props);
this.state = {
company: {
legalName: ''
},
openCorporatesCompany: {}
};
}
handleLegalNameChange = (legalName) => {
let company = _.cloneDeep(this.state.company);
company.legalName = legalName;
this.setState({
company
})
};
static getDerivedStateFromProps(next, prev) {
let newState = _.cloneDeep(prev);
let {openCorporates: {getEntityAttribute}} = next;
if (getEntityAttribute && getEntityAttribute.value) {
let openCorporatesCompany = JSON.parse(getEntityAttribute.value);
let company = _.cloneDeep(newState.company);
company.legalName = openCorporatesCompany.name;
newState.openCorporatesCompany = openCorporatesCompany;
newState.company = company;
return newState;
}
return null;
}
render() {
console.log(this.state);
return (
<Input
label='Legal Name'
placeholder='Legal entity name...'
type='text'
subtext='Use the name your customers or clients will recognize'
onChange={this.handleLegalNameChange}
value={this.state.legalName}
/>
);
}
}
export const VerificationContainer = compose(
connect(mapStateToProps, mapDispatchToProps)
graphql(GetEntityAttributeQuery, {
name: "openCorporates",
options: (props) => ({
variables: {
entityId: props.currentEntity.id,
type: EntityAttributes.TypeOpenCorporates
}
})
})
)(Verification);
render 中 console.log(this.state) 的控制台输出如下所示:
如您所见,该字段的状态已更新为 company.legalName。但是,它永远不会被填充到输入框中:
为什么输入没有更新为新状态?就好像在 getDerivedStateFromProps 之前调用了渲染。
【问题讨论】:
标签: reactjs graphql react-apollo