reactjs - React-Apollo - 在 getDerivedStateFromProps 之前调用渲染
问题描述
我有一个包含用户验证表单的组件。该组件在挂载时运行 graphql 查询。在验证组件中,我需要使用来自 graphql 查询的数据来设置状态,以便我可以使用它来更新任何值,然后将它们与表单一起提交。从那以后,我了解到getDerivedStateFromProps
并且正在努力从该数据中填充一个新状态。但是,数据在 DOM 中不可用。就好像render
之前被调用过一样getDerivedStateFromProps
。
这是组件:
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);
console.log(this.state)
in的控制台输出render
如下所示:
如您所见,该字段的状态更新为company.legalName
. 但是,它永远不会被填充到输入框中:
为什么输入没有更新为新状态?就好像之前调用了渲染getDerivedStateFromProps
。
解决方案
我知道你在 react 和组件更新方面的挣扎,但我想没有什么可以摆脱它的;80% 我猜你应该尝试任何不同的生命周期方法。过去有componentWillReceiveProps用于异步调用,但由于它被标记为不安全(我猜)你应该尝试getDerivedStateFromProps(props, state)
getDerivedStateFromProps(props, state) {
console.log("*************** PROPS:", props);
let { openCorporates: { getEntityAttribute } } = props;
if (getEntityAttribute && getEntityAttribute.value) {
let openCorporatesCompany = JSON.parse(getEntityAttribute.value);
let company = _.cloneDeep(this.state.company);
company.legalName = openCorporatesCompany.name;
this.setState({
openCorporatesCompany,
company
})
}
}
考虑到我没有运行代码段。
推荐阅读
- list - 在 Prolog 列表中的每个元素之后插入元素
- macos - Mac系统上的“zsh:找不到命令:mvn” intellij ver 2020.2社区
- python - JSON 解码器错误 - 需要 ',' 分隔符:第 1 行第 22 列(字符 21)
- spring-boot - 使用 Spring BOOT 创建访问网页的角色要求
- java - 如何制作总和为 n(n-1)/2 的数字列表
- visual-studio-code - VSCode对vim的ci的快捷命令是什么
VSCode 有办法在标签之间进行选择吗?而且我的意思不仅仅是折叠和取消折叠,我的意思是选择开始标签和结束标签之间的所有内容。
- android - 自定义 TextInputLayout 在后按时设置错误的值
- bash - 如何将多行输出存储在单独的变量中?
- python - for/else 块中的错误打印输出错误触发
- python - 字典/json 赋值 - python