繁体   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