简体   繁体   中英

React.js component run error.Uncaught TypeError: Cannot read property '0' of undefined

I am trying to create a Fetch component, which should send a POST request return a response content. And meanwhile I create a NameForm component, which generate a data to Fetch component to send request. My problem is when I use this.state.result.queryResults[0] , I got a error in chrome like this: 在此处输入图片说明

Here is my js code:

        import React, {Component} from 'react';
        import Request from 'react-http-request';

        class Fetch extends React.Component {

            constructor() {
                super();
            }

            render() {
                return (
                    <Request
                        url='http://localhost:8080/path'
                        method='post'
                        accept='application/json'
                        type="application/json"
                        send={this.props.args}
                        verbose={true}
                    >
                        {
                            ({error, result, loading}) => {
                                if (loading) {
                                    return <div>loading...</div>;
                                } else {
                                    return <div>{result.text}</div>;
                                }
                            }
                        }
                    </Request>
                );
            }
        }

        class NameForm extends React.Component {
            constructor() {
                super();
                this.state = {value: '', result: []};

                this.handleChange = this.handleChange.bind(this);
                this.handleSubmit = this.handleSubmit.bind(this);
            }

            handleChange(event) {
                this.setState({value: event.target.value});
            }

            handleSubmit(event) {
                var content = this.state.value;

                var split = content.split(/\s+/);

                var queryObject = new Object();

                queryObject.law = null;
                queryObject.character = null;
                queryObject.lawRule = null;
                if (split.length == 1) {
                    queryObject.law = split[0];
                }
                else if (split.length == 2) {
                    queryObject.law = split[0];
                    queryObject.character = split[1];
                }
                else if (split.length > 2) {
                    queryObject.law = split[0];
                    queryObject.character = split[1];
                    queryObject.lawRule = split[2];
                }
                var json = JSON.stringify(queryObject);



                this.setState({result: (<Fetch args={json}/>)});

                event.preventDefault();
            }

            render() {
                return (
                    <div>
                        <form onSubmit={this.handleSubmit}>
                            <label>
                                Name:
                                <input type="text" value={this.state.value} onChange={this.handleChange}/>
                            </label>
                            <input type="submit" value="Submit"/>
                        </form>
                        <table>
                            <thead>
                            <tr>
                                <th>GraphName</th>
                                <th>Relation</th>
                                <th>Content</th>
                                <th>KeyWord</th>
                            </tr>
                            </thead>
                            <tboy>{this.state.result.queryResults[0]}</tboy>
                        </table>

                    </div>
                );
            }
        }

        ReactDOM.render(<NameForm/>, document.getElementById('react'))

And my post response is a json like this:

{
        "path": {
            "law": "MyLaw",
            "character": "C1",
            "lawRule": null
        },
        "queryResults": [
            {
                "graphName": "MyLaw/C1",
                "relation": "self",
                "content": "I am C1",
                "keyword": {
                    "a": 0.4296310331415849,
                    "b": 0.22019926949447058,
                    "c": 0.16514945212085294,
                    "d": 0.16514945212085294,
                }
            },
            {
                "graphName": "MyLaw/C1/C1.1",
                "relation": "child",
                "content": "I am C1.1",
                "keyword": null
            },

            {
                "graphName": "MyLaw/C1/C1.2",
                "relation": "child",
                "content": "I am C1.2",
                "keyword": null
            },
            {
                "graphName": "MyLaw/C1/C1.3",
                "relation": "child",
                "content": "I am C1.3",
                "keyword": null
            },

        ]
    }

In the constructor, we defined the state initial value

        constructor() {
            super();
            this.state = {value: '', result: []};

            this.handleChange = this.handleChange.bind(this);
            this.handleSubmit = this.handleSubmit.bind(this);
        }

So, the initial value of result is [] .

And in handleSubmit , you will fetch data for result.

        handleSubmit(event) {
            ...
            this.setState({result: (<Fetch args={json}/>)});
            ...
        }

So, before submitting and data being fetched, the result is []

So, please change

 <tboy>{this.state.result.queryResults[0]}</tboy>

To

 <tboy>{this.state.resultthis.state.result.queryResults[0]}</tboy>

At your initial render results state is an empty array and it remains like it till the response from fetch call is received. So

<tbody>{this.state.result.queryResults[0]}</tbody>

fails, as result.queryResults is undefined.

So you need a conditional check.

<tbody>{this.state.result.length > 0? 
     this.state.result.queryResults && 
     this.state.result.queryResults[0]: 
 null}</tbody>

It is giving you error because when first time it renders it can not find queryResult until the request hit the server.

Try this:

<tboy>
    {
        this.state.result.queryResults
            ?
            this.state.result.queryResults[0]
            : null
    }
</tboy>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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