【问题标题】:Child component returns props as null子组件将 props 返回为 null
【发布时间】:2019-10-09 23:40:24
【问题描述】:

我正在从父组件的 api 获取数据,并将数据作为道具发送给子组件。当我尝试安慰道具时,它返回 null。不知道为什么。但是当子组件再次渲染时,道具会显示出来

这是父组件

componentWillMount(){
        fetch('http://13.234.252.37:5000/api/user_information/'+ this.props.propUser_id)
        .then(response => response.json())
        .then(data => {
            console.log(data);
            this.setState({fileUploadedData: data.Documents, dashboardPiscore: data.piscore}, () => {
                console.log("set sytate", this.state.fileUploadedData);
            })
        })
    }

return(
this.state.dashboardHome ? <DashboardHome analysisData={this.state.fileUploadedData} /> : null 
)

这是子组件

class dashboardHome extends Component{
  constructor(props){
    super(props);
    console.log("props in cons", this.props);
    this.state= {
      annualIncome: '0',
      monthlyExpense: '0',
      monthlySavings: '0',
    }
  }

  componentDidMount(){
    console.log("props in home", this.props);
    if(this.props.analysisData !== null) 
    {
      this.setState({
      annualIncome: this.props.analysisData[0].Salary,
      monthlyExpense: this.props.analysisData[1].average_monthly_expense,
      monthlySavings: this.props.analysisData[1].average_monthly_savings
      })
 render(){  
return(
<div>//dashboard</div>
)
}

当组件第一次渲染时,道具被控制台为空。当我再次渲染它时,道具值被设置。请帮助我在第一次渲染组件时设置道具。 道具现在为空。当我单击仪表板的其他选项卡并再次返回仪表板时,道具已按预期正确设置

【问题讨论】:

  • 为什么在 componentWillMount 中使用 fetch ?正确的方法应该是componentDidMount
  • 即使我在 DidMount 中使用它也无法正常工作。我刚试过。

标签: reactjs react-props


【解决方案1】:

通常建议使用componentDidMount 而不是componentWillMount。另外,您自己说您正在从 Api 获取数据。在获取数据并存储在 state 中之前,传递给 child 的初始 props 当然是空的。如果这会导致问题,您可以考虑在实际数据到达之前使用一些默认值。或者你也可以在数据到达之前完全不渲染子组件,并显示加载指示器。

【讨论】:

  • 没有默认值将无法正常工作,因为此应用程序要求用户输入的数据显示在仪表板上(如图形的表示形式)。在这种情况下设置一个默认值是否可行。
  • 请建议我一种更好的方法,将我从 API 获得的数据分配给道具
  • @HareiniSreethi 在数据到达之前显示加载指示器或其他内容
  • 好的,我会尝试使用加载组件。我能知道我的孩子什么时候会收到父母的道具吗
  • @HareiniSreethi 当父母写&lt;Child para={x}/&gt;时,孩子总是收到这个道具,不管x的值是否未定义。
【解决方案2】:

您可以在条件语句中添加短路吗?

this.state.dashboardHome && this.state.dashboardHome ?

所以它会在第一次忽略它,因为它最初会评估为 false,然后在第二次渲染时,它会看到数据,解析为 true,然后运行其余的三元语句。这样你就不会收到错误。我在使用 Hooks 时遇到了这个问题,它通常可以解决它。

https://reactjs.org/docs/conditional-rendering.html 内联 If 与逻辑 && 运算符部分

【讨论】:

    猜你喜欢
    • 2018-07-25
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多