簡體   English   中英

this.props在子組件的console.log中工作,但不渲染

[英]this.props working in console.log of child component, but not rendering

我正在將最近更新的狀態變量傳遞給子組件。 在該子組件中,我可以console.log(this.props.response.message)並查看最近更新的變量的預期結果。 但是, this.props.response.message不會呈現。 我需要在React Lifecycle方法中執行一些操作嗎? 如果是這樣,那會是什么樣子?

父組件

 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> 

子組件

 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> 

同樣,在該子組件中,我可以console.log(this.props.response.message)並查看最近更新的變量的預期結果。 但是,它不會渲染。

您正在result道具中傳遞數據,

<FormSuccess result={this.state.response} />

你應該這樣使用

{this.props.result} // Normal case

如果您要得到result對象,並想從中檢索message ,請使用它,

{this.props.result.message}

另外,您應該注意數據類型。 如果數據類型是json或類似的內容,則無法渲染它,但可以在控制台上編寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM