I'm passing a recently updated state variable to a child component. In that child component I'm able to console.log(this.props.response.message)
and see the expected result of the recently updated variable. However, the this.props.response.message
is not rendering. Do I need to perform some action in a React Lifecycle method? If so, which one and how would that look?
Parent Component
import React, { Component } from 'react'; import axios from 'axios'; import FormSuccess from './FormSuccess'; export default class NewRuleForm extends Component { constructor(props) { super(); this.state = { submitSuccess: false, isOpen: false, response: {} }; this.handleSubmit = this.handleSubmit.bind(this); } async handleSubmit(e) { let response = await axios.post('localhost:5000', { data: e.target.id.value } ) if (response.data.success) { this.setState({ submitSuccess: true, response: response.data }) } else { this.setState({ submitSuccess: false, }) } return response } } render() { if (this.state.submitSuccess === true) { return <FormSuccess result={this.state.response} /> } return ( <form onSubmit={this.handleSubmit}> <input type="text" name="id"/> </form> ) } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Child Component
import React, { Component } from 'react'; export default class FormSuccess extends Component { constructor(props) { super(); } render() { console.log(this.props.result.message) // works return ( <div> <h1>Successful Form Submission</h1> {/* below doesn't render */} <p>{this.props.result.message}</p> </div> ); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Again, in that child component I am able to console.log(this.props.response.message)
and see the expected result of the recently updated variable. However, it does not render.
You are passing data in result
prop,
<FormSuccess result={this.state.response} />
You should use it like this,
{this.props.result} // Normal case
If you are getting object in result
and want to retrieve message
from it then use this,
{this.props.result.message}
Also you should be careful about data type. If data type is json or something like that, you cant render it but you can write on console.
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.