簡體   English   中英

ReactJS中初始狀態的未定義值

[英]Undefined value for initial state in ReactJS

我對ReactJS還是很陌生,現在遇到了讓我完全困惑的事情。

我創建了許多呈現Bootstrap模式的組件。 此外,我通過componentDidMount函數從服務器獲取初始狀態參數。 我的組件結構如下所示:

<App>
  <Modal Lauch Button /> 

  <Modal>
   <Modal Header />
   <Modal Body />     <-- here's the problem
  </Modal>
</App>

而且我的初始狀態數組的形式(當然是JSON編碼):

array:5 [▼
   ...
   ...
   "private" => true
   "files" => array:2 [▼
       1 => array:7 [▼
          "id" => 0
          "route" => "some route"
          ...
          ...
       ]
       2 => array:7 [▼
          "id" => 1
          "route" => "some other route"
          ...
          ...
       ]
   ]
]

和我的(縮小的)React應用程序是這樣的:

<script type="text/babel">

    var L5fmModalBody = React.createClass({

        render: function() {

            return(
                <Modal.Body>
                    <Grid fluid={true}>
                        <Row>
                            {
                                this.props.files.map(function (file) {
                                    return <L5fmModalBodyFileContent id={file.id} route = {file.route} / >
                                })
                            }
                        </Row>
                    </Grid>
                </Modal.Body>
            );
        }

    });

    var L5fmModalBodyFileContent = React.createClass({

        render : function() {
            return(
                <Col xs={6} md={4} className="img-row">
                    <div className="thumbnail thumbnail-img">
                        <img key={this.props.id} src={this.props.route} />
                    </div>
                </Col>
            );
        }

    });

    var L5fmModal = React.createClass({

        getInitialState : function() {
            return {
                data : []
            };
        },

        componentDidMount: function() {
            $.ajax({
                url: 'L5fm/setInitialState',
                dataType: 'json',
                cache: false,
                success: function(data) {
                    this.setState({data: data});
                    console.log(data);
                    console.log(this.state.data);
                }.bind(this),
                error: function(xhr, status, err) {
                    console.error(this.props.url, status, err.toString());
                }.bind(this)
            });
        },

        render: function() {

            return(

                <Modal {...this.props} bsSize="large" aria-labelledby="contained-modal-title-lg">
                    <Modal.Header closeButton>
                        <div className="header-button-group">
                            some buttons
                        </div>
                    </Modal.Header>

                    <L5fmModalBody files={this.state.data.files} />
                </Modal>
            );
        }

    });


    var App = React.createClass({
        getInitialState: function() {
            return { lgShow: false };
        },
        render: function() {
            let lgClose = () => this.setState({ lgShow: false });

            return (
                 <Button bsStyle="primary" onClick={()=>this.setState({ lgShow: true })}>
                    Launch large demo modal
                 </Button>
                 <L5fmModal show={this.state.lgShow} onHide={lgClose} />
            );
        }
    });

    ReactDOM.render(<App />, document.getElementById("modal"));

</script>

每當我運行應用程序時,都會出現以下錯誤:

L5fmModalBody_renderTypeError:this.props.files.map不是函數。 (在“ this.props.files.map”中,“ this.props.files.map”未定義)

如果我在<Modal>組件中console.log(this.state.data.files) ,它還顯示this.state.data.files是未定義的嗎? 顯然我不知道發生了什么。 我也嘗試過使用componentWillMount來獲取數據,但這也沒有幫助。 我究竟做錯了什么?

謝謝!


更新

我想我又走了一步。 實際的問題不是開始時this.set,statenull ,因為在調用componentDidMount並設置了“新”狀態之后,UI會再次呈現。 此外,我發現JSON顯然將關聯數組作為對象進行處理,並且我相信我無法在對象上調用map

有任何想法嗎?

是的,當然,它會引發錯誤,因為您正在傳遞此<L5fmModalBody files={this.state.data.files} />並且您的狀態已在data : []聲明data : []這意味着首次渲染發生時數據只是一個空白數組,並且完成后,您的組件將在瀏覽器上呈現,然后調用L5fmModal的componentDidMount ,它將從數據庫獲取數據,並再次更新狀態和呈現函數,並且數據具有文件字段,但是當數組只是一個空時,第一次加載該怎么辦?該時間文件字段未定義,因此您必須在L5fmModalBody實現以下提到的代碼

     {
(type of this.props.files != 'undefined')? this.props.files.map(function (file) {
                                        return <L5fmModalBodyFileContent id={file.id} route = {file.route} / >
                                    }):null                                
}

或者您也可以通過以下方式阻止自己使用L5fmModal

{this.state.data.length>0 ? <L5fmModalBody files={this.state.data.files} />:null}

多虧了Dhaval Patel,我終於有了這個問題的答案。 問題不在於初始狀態的null值,因為在調用componentDidMount時,UI會再次呈現並從服務器接收更新后的狀態。 實際的問題是JSON將關聯數組視為對象 ,因此無法調用簡單map

我剛換

{
    this.props.files.map(function (file) {
        return <L5fmModalBodyFileContent id={file.id} route = {file.route} / >
    })
}

{
    Object.keys(object).map(
        function(d){
            return <L5fmModalBodyFileContent id={object[d].id} route={object[d].route} />
    })
}

其中object = this.props.files ,它就像一個魅力!

為了避免使用(最初)未定義對象的錯誤

{this.state.data.length!=0 ? <L5fmModalBody files={this.state.data.files} />:null}

<Modal />組件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM