繁体   English   中英

反应Javascript渲染错误

[英]React Javascript render error

我目前正在开发我的Web应用程序,并且在其中一个组件中,我正在通过以下方式获取一些数据库数据:

var SelectHund = React.createClass({
          getInitialState: function() {
            return {
              hunde:{}
            };
          },
          componentDidMount: function(){
            var that = this;
            $.ajax({
              type: "POST",
              url: "/foodoo/index.php?method=getDogs",
              data: JSON.stringify(planData),
              success: function(response){
                var hunde = JSON.parse(response);
                console.log(hunde);
                if(hunde.length >= 1){

                  that.setState({
                    hunde: hunde
                  });
                }
              },
              error: function(){
              }
            });
          },
          render: function(){
            if(this.state.hunde.length <= 0){
              return(<div>test</div>);
            }else{
              // console.log(this.state);
              // console.log(this.state.hunde);
              var POS = this.state.hunde.map(function(i){
                  console.log(i);
                  return  <option key={i.id} value={i.weight}>i.name</option>;
              });
              return(<select className="selectHund" name="hund">{POS}</select>);
            }
          }
        });

该组件的调用方式如下:

return (
                    <div>
                      <h2>{this.state.planname}<span className="close">x</span></h2>
                      <SelectHund changeHund={this.changeHund} />
...

通过该方法,我使用map函数遍历了响应对象,console.log的“ i”返回单个对象,如下所示:

Object {id: "1", user_id: "1", name: "Balou", weight: "15", activity: "1"…}
Object {id: "2", user_id: "1", name: "Franzi", weight: "70", activity: "1"…}

所以我想对象处理没有错误。

不幸的是,我一直在控制台中收到此错误:

Uncaught Error: Invariant Violation: SelectHund.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.

我尝试在ajax函数外部调用外部函数,以查看这是否可能导致错误,但不会。 其他一些业余爱好者也尝试调试它失败-所以我需要您的帮助^^

您的render方法不返回任何内容。 您需要移动以下行:

return(<select onChange={that.props.changeHund} className="selectHund" name="hund">{POS}</select>);

success回调之外。 然后您将面临其他问题,但这是正确的方向。

与其在render函数中执行Ajax,不如将其移至另一个生命周期方法(例如componentDidMount )或数据模型(例如Flux)。

然后使用状态或道具来处理内部组件数据(在您的示例中为hunde对象)。 遵循docs / tutorials中的一些示例可以帮助您入门。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM