简体   繁体   中英

How to update state with Relay QueryRenderer props

I have a react component with a form for updating database records. Here's the thing: the data is loaded with React-Relay QueryRenderer component as follows:

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. However, I need to call the update with this.state values. I need a way to setState with props values.

I have tried with componentDidMount and using refs both string refs and callback ones to get defaultValue from Inputs. I got undefined values when calling 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. 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

Use componentWillReceiveProps in your Form component

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM