[英]How to update state with Relay QueryRenderer props
I have a react component with a form for updating database records. 我有一个带有更新数据库记录形式的React组件。 Here's the thing: the data is loaded with React-Relay QueryRenderer component as follows:
事情是这样的:数据通过React-Relay QueryRenderer组件加载,如下所示:
class Update extends Component {
//constructor..
//some stuff
render() {
return(
<QueryRenderer
environment={environment}
query={UpdateQuery}
render={({error, props}) => {
//validations
return (
<Form loading={this.state.loading}>
//inputs
</Form>
)...
}/>
)}
The props variable is supposed to store the result from server response if successful. 如果成功,props变量应该存储服务器响应的结果。 However, I need to call the update with this.state values.
但是,我需要使用this.state值调用更新。 I need a way to setState with props values.
我需要一种使用props值设置setState的方法。
I have tried with componentDidMount and using refs both string refs and callback ones to get defaultValue from Inputs. 我尝试使用componentDidMount并同时使用refs和string refs以及callback来从Inputs获取defaultValue。 I got undefined values when calling this.refs
调用this.refs时得到未定义的值
For now, it works if I call a function within QueryRenderer render function that sets the state with props if state is empty. 目前,如果我在QueryRenderer渲染函数中调用一个函数(如果状态为空)则用props设置状态,则它可以工作。 Eg
例如
function initValues(props){
if(!this.state.name)
this.setState({name: props.result.name})
}
But it results in an anti-pattern (pure render method) that I need to solve. 但这会导致我需要解决的反模式(纯渲染方法)。
Edit: For anyone wondering how I solved this. 编辑:对于任何想知道我如何解决此问题的人。 Thanks to charlie's answer I managed to create a UpdateForm component wrapper that receives the props from QueryRenderer, and in order to update my parent's component state I passed my handleChange function as props to my FormUpdate component
感谢charlie的回答,我设法创建了一个UpdateForm组件包装器,该包装器从QueryRenderer接收了道具,并且为了更新我父母的组件状态,我将handleChange函数作为道具传递给了FormUpdate组件
Use componentWillReceiveProps in your Form component 使用componentWillReceiveProps在您的表单组件
class Form extends React.Component {
...
componentWillReceiveProps(nextProps) {
if (nextProps.loading) return
this.setState({
name: nextProps.name
})
}
...
}
This will only set the state once as soon as the data is available, since QueryRenderer only calls render once after the data has loaded. 这只会在数据可用后立即设置状态一次,因为QueryRenderer仅在数据加载后调用一次render。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.