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

时间:2019-05-06 05:32:15

标签: javascript reactjs

我正在将最近更新的状态变量传递给子组件。在该子组件中,我可以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)并查看最近更新的变量的预期结果。但是,它不会渲染。

2 个答案:

答案 0 :(得分:2)

您正在以result属性传递数据,

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

您应该像这样使用它,

{this.props.result} // Normal case

如果您在result中获取对象并想从中检索message,请使用它,

{this.props.result.message}

答案 1 :(得分:2)

此外,您还应该注意数据类型。如果数据类型是json或类似的内容,则无法渲染它,但可以在控制台上编写。