【问题标题】:How to send conditional props from Parent to Child. (send if only array is not empty)如何将条件道具从父母发送给孩子。 (如果只有数组不为空,则发送)
【发布时间】:2019-09-03 12:58:02
【问题描述】:

我想显示我从Choices 组件中的 API 获得的 JSON 数据。

class ShowChoice extends React.Component{
    // var out=this.props.output Why is it not working here? Why is it showing error?
    render() {
        var out=this.props.output // Why is it not working above render????
        return(
            <div>Render out[0].id here </div>
        )
    }
}

output 是一个数组,它有

output =[{'id':1}, {'choice_text':'some choice'}]

问题是,每当我启动应用程序或应用程序重新呈现自身时,输出 是未定义的,它会抛出一个错误说

TypeError: Cannot read property 'id' of undefined

console.log(out[0].id)

  1. 我该如何解决这个问题?
  2. 我想如果我能以某种方式发送道具,只要输出有一定长度,那么我可以解决问题
  3. 为什么注释行 var out=this.props.outputrender 上方不起作用?

【问题讨论】:

    标签: reactjs react-props react-component


    【解决方案1】:

    在渲染任何东西之前,您必须首先检查 输出 是否已定义。 喜欢

    class ShowChoice extends React.Component{
    
        render() {
            const { output } = this.props
            if (!output) {
               return null;
            }
            return(
                <div>Render output[0].id here </div>
            )
        }
    }
    

    【讨论】:

      【解决方案2】:

      上面的var out=this.props.output;在构造函数中不起作用

      <pre>
      constructor(props) {
         super(props);
         var out=this.props.output;
        }
      </pre>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-28
        • 2020-12-17
        相关资源
        最近更新 更多