简体   繁体   English

为什么对象不能作为 React 子对象?

[英]Why are objects not valid as a React child?

I hope anyone can help me!我希望任何人都可以帮助我! I cant render my object in the right way.我无法以正确的方式渲染我的对象。

My JSON:我的JSON:

{"status":"Entregado","_id":"5f490dd9b3f5192230a8f536","products":[{"_id":"5f44eaa1cf215b305449e216","name":"Reto Gratuito Medita Healing","price":0,"createdAt":"2020-08-25T10:40:33.845Z","updatedAt":"2020-08-25T10:40:33.845Z","__v":0,"count":1}],"details":"dimebag_666","client_email":"jobroman83@gmail.com","state":"CDMX","address":"acueducto","zip":"16200","client_id":"5f2ac527543c3835d028337c","amount":0,"createdAt":"2020-08-28T13:59:53.129Z","updatedAt":"2020-09-07T09:03:39.117Z","__v":0}

I rendered almost all the component with this code:我用这段代码渲染了几乎所有的组件:

const SingleOrder = (props) => {

    const token = getCookie('token')  //// <-- right one
    const Id = getCookie('token')  



    const [order, setOrder] = useState({});
    const [error, setError] = useState(false);
    const [statusValues, setStatusValues] = useState([])

    const loadSingleOrder = orderId => {
        read(orderId,token).then( data => {
            if (data.error){
                setError(data.error)
            } else {
                setOrder(data)
            }
        })
    }

    const loadStatusValues = () => {
        getStatusValues(Id, token).then(data => {
            if (data.error){
                console.log(data.error)
            } else{
                setStatusValues(data)
            }
        })
    }

    const handleStatusChange = (e, orderId) => {
        // console.log('update order status')
        updateOrderStatus(Id, token ,orderId, e.target.value).then(
            data => {
                if (data.error){
                    console.log('status update failed')
                } else {
                    // setRun(!run)
                    loadSingleOrder(orderId)
                    console.log('changed')
                    alert('Has Cambiado el estatus')
                }
            }
        )
    }

    const showStatus = (order) => {
        return (
            <div className='form-group'>
            <h5 className='mark mb-4'>Estatus: {order.status}</h5>
            <select className='form-control' 
                    onChange={(e) => handleStatusChange(e, order._id)}>
                <option>Actualizar estado de orden</option>
                {statusValues.map((status, index) => (
                    <option key={index} value={status}>{status}</option>
                ) )}

            </select>
        </div>
        )
    }

    


    const showInput = (key, value) => {
        return (
            <div className="input-group mb-2 mr-sm-2">
                <div className="input-group-prepend">
                    <div className="input-group-text">{key}</div>
                </div>
                <input type="text" value={value} className="form-control" readOnly/>
            </div>
        )
    }

    useEffect (() => {
        const orderId = props.match.params.orderId
        loadSingleOrder(orderId)
        loadStatusValues()
    },[props])

    const showOrderList = () => {
        return (
            <div className="card mr-2 mt-2 mb-5">
                <h5 className="mb-1 mt-2 text-center bg-primary"  style={{color:'red'}}>Numero de Orden: {order._id}</h5>
                <ul className="list-group">
                                    <li className='list-group-item'>
                                    {/* {o.status} */}
                                        {showStatus(order)}
                                    </li>
                                    <li className='list-group-item'>ID cliente: {order.client_id} </li>   
                                    <li className="list-group-item">Télefono: {order.client_phone}</li>
                                    <li className="list-group-item"  style={{fontWeight:'bold'}}> Cuenta de <i class="fab fa-instagram"/>  vinculada al Taller: {order.details}</li>
                                    <li className="list-group-item">E-mail: {order.client_email}</li>
                                    <li className='list-group-item'>Total de la orden: ${order.amount}</li>
                                    <li className='list-group-item' style={{fontWeight:'bold'}}>Comprado el dia:{" "}
                                            {moment(order.createdAt).locale('es').format('LL')}
                                        </li>
                                    <li className='list-group-item'>Dirección : {order.address}</li>
                                    <li className='list-group-item'>Estado : {order.state}</li>
                                    <li className='list-group-item'>Código Postal: {order.zip}</li>
                                    
                           if a put this code the problem is --> "TypeError: order.products is undefined"     {order.products.map((p, pIndex) => (
                                        <div className='' key={pIndex} style={{padding:'20px', border:'1px solid #e6c4ba'}}
                                        
                                        >
                                            {showInput('Nombre del producto:', p.name)} 
                                            {/* {showInput('Precio del producto $:', p.price)}  
                                            {showInput('Cantidad pedida del producto:', p.count)}  
                                            {showInput('ID del producto:', p._id)}    */}
                                </div>
                            ))}
                              if i only put this i recived --> {order.products}

Error: Objects are not valid as a React child (found: object with keys {_id, name, price, createdAt, updatedAt, __v, count}). If you meant to render a collection of children, use an array instead.
                                </ul>
            
            </div>
        )
    }



    return(
        <Layout>
            <div className='container'>
                {/* {showOrderList()} */}
                {JSON.stringify(order)}
            </div>
        </Layout>
    )

}

But when i want to render the products inside of my object i cant Render them, its because of that i receiving the message :但是当我想在我的对象内部渲染产品时,我无法渲染它们,因为我收到了消息:

Error: Objects are not valid as a React child (found: object with keys {_id, name, price, createdAt, updatedAt, __v, count}).错误:对象作为 React 子对象无效(找到:带有键 {_id、name、price、createdAt、updatedAt、__v、count} 的对象)。 If you meant to render a collection of children, use an array instead.如果您打算渲染一组子项,请改用数组。

{order.products}

I have to render this in the right way, I tried with map etc.. I'm always getting this error.我必须以正确的方式呈现它,我尝试使用map等。我总是收到此错误。

You can use map() like this:您可以像这样使用map()

<ul>
{order?.products.map(item => (
    <>
      <li>{item.name}</li>
      <li>{item.price}</li>
      <li>{new Date(item.createdAt)}</li>
      <li>{new Date(item.updatedAt)}</li>
    </>
  )
}
</ul>

you can also include the rest of the object items like id or count if necessary.如有必要,您还可以包括其余的对象项目,如idcount

using <> </> tags are a short way of <React.Fragment> </React.Fragment> respectively.使用<> </>标签分别是<React.Fragment> </React.Fragment>一种简短方式。

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

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