簡體   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