简体   繁体   English

间歇性的React Uncaught错误:对象无效作为React子级

[英]Intermittent React Uncaught Error: Objects are not valid as a React child

I have a Header component which renders some links, depending on whether a user is signed in or not. 我有一个Header组件,它根据用户是否登录来呈现一些链接。

This component loads fine, displays signin and signup links fine. 该组件加载正常,显示登录和注册链接正常。 Clicking on those links takes me to those components, which function as they should. 单击这些链接会将我带到这些组件,它们将发挥应有的作用。 Once I sign in, the header changes to display a signout link. 登录后,标题将更改为显示注销链接。

However, when I sign out, things go wrong. 但是,当我退出时,情况会出错。 The signin and signup links display fine, but they are no longer functional. 登录和注册链接显示正常,但是它们不再起作用。 Clicking on the signup link gives the following error: 单击注册链接会出现以下错误:

Uncaught Error: Objects are not valid as a React child (found: object with keys {}). 未捕获的错误:对象作为React子对象无效(找到:带有键{}的对象)。 If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. 如果您打算渲染孩子的集合,请改用数组或使用React附加组件中的createFragment(object)包装对象。 Check the render method of Signin . 检查Signin的渲染方法。

Clicking on the link again produces this: 再次单击链接将产生以下结果:

bundle.js:4297 Uncaught TypeError: Cannot read property 'getHostNode' of null bundle.js:4297未捕获的TypeError:无法读取null的属性'getHostNode'

I've read similar questions on here, and typically they involved someone trying to render an object as opposed to one of its properties. 我在这里读过类似的问题,通常它们涉及试图渲染对象而不是其属性之一的人。 However, this isn't the case here-or am I missing something? 但是,这里不是这种情况-还是我错过了什么?

My code: 我的代码:

Header: 标题:

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {Link} from 'react-router';

class Header extends Component{
    renderLinks(){
        if(this.props.authenticated){
            return <li className="nav-item ">
                <Link className="nav-link" to="/signout">Sign Out</Link>
            </li>
        }else{
            return [<li className="nav-item page-scroll" key={1}>
                        <Link className="nav-link page-scroll" to="/signin">Sign In</Link>
                    </li>,
                    <li className="nav-item" key={2}>
                        <Link className="nav-link page-scroll" to="/signup">Sign Up</Link>
                    </li>
           ]
        }
    }

    render() {
        return (
            <div className="container-fluid header">
                <nav className="navbar navbar-toggleable-md navbar-inverse bg-inverse">
                    <div className="navbar-nav">
                            <Link to="/" className="navbar-brand">
                                    <img alt="Trellis" src="../../images/trellis.png" />
                            </Link>
                            <ul className="nav navbar-nav">
                                {this.renderLinks()}
                            </ul>
                        </div>

                </nav>
            </div>
        );
    }
}

function mapStateToProps(state){
    return{
        authenticated: state.auth.authenticated
    };
}
export default connect(mapStateToProps)(Header);

Signin component: 登录组件:

import React, { Component } from 'react';
import { reduxForm, Field } from 'redux-form';
import * as actions from '../../actions';
import { connect } from 'react-redux'; 
import { Link } from 'react-router';

class Signin extends Component {

    handleFormSubmit({ email, password }) {
        this.props.signInUser({email, password});
    }

    renderInput(field) {
        if(!field.className) { field.className = "form-control" }
        if(!field.type) { field.type = "text" }

        return (
            <div>
                <Field name={field.name} id={field.name} type={field.type} className={field.className} component="input" />
            </div>
        )
    }
    renderAlert(){
        if(this.props.errorMessage){
            return(
                    <div className="alert alert-danger">
                        <strong>Oops!</strong> {this.props.errorMessage}
                    </div>
                );
    }
}

    render() {
        const { handleSubmit } = this.props

        return (
            <form className="sign-in" onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
                <fieldset className="form-group">
                    <label>Email:</label>
                    {this.renderInput({ name: "email", type: "email" })}
                </fieldset>
                <fieldset className="form-group">
                    <label>Password:</label>
                    {this.renderInput({ name: "password", type: "password" })}
                </fieldset>
                <div className="password-forgot">
                    <Link to="/reset-password">I forgot my password</Link>
                </div>
                {this.renderAlert()}
                <button action="submit" className="btn btn-primary">Sign in</button>
            </form>
        )
    }
}

function mapStateToProps(state){
    return{errorMessage: state.auth.error};
 }

Signin = connect(mapStateToProps, actions)(Signin)

export default reduxForm({
  form: 'signin'
})(Signin)

Signout component: 退出组件:

import React, {Component} from 'react';
import {connect} from 'react-redux';
import * as actions from '../../actions';

class Signout extends Component {
    componentWillMount() {
        this.props.signOutUser();
    }
    render() {
        return <div>Sorry to see you go!</div>;
    }
}

export default connect(null, actions)(Signout);

Signin action: 登录操作:

export function signInUser(props) {
    const { email, password } = props;
    return function(dispatch){
        axios.post(`${ROOT_URL}/signin`, {email, password})
            .then(response => {
                localStorage.setItem('user', JSON.stringify(response.data));
                dispatch({ type: AUTH_USER });
                browserHistory.push('/dashboard');
        })
            .catch((err) => {
                console.log(JSON.stringify('login error:', err));
                dispatch(authError(SIGNIN_FAILURE, 'Bad login credentials'));
        });
    };
}

Signout action: 登出动作:

export function signOutUser() {
    localStorage.clear();
    return { type: UNAUTH_USER };
}

(As per the comments on the original post) (根据对原始帖子的评论)

The issue was in the SignIn render component you call the renderAlert() function which returns this.props.errorMessage as part of the JSX element. 问题出在SignIn渲染组件中,您调用renderAlert()函数,该函数将this.props.errorMessage作为JSX元素的一部分返回。 This was the only part of the JSX rendered by SignIn which could've been as issue (as per your code). 这是SignIn呈现的JSX的唯一部分,可能会成为问题(根据您的代码)。

Turns out this.props.errorMessage was actually an object not a string as you had thought, hence the error regarding an object as a React child. 原来this.props.errorMessage实际上是一个对象,而不是您所想的字符串,因此将对象视为React子对象时出错。

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

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