在反应中映射数组数据

时间:2020-09-08 19:19:14

标签: reactjs react-native

我目前正在学习react,我想显示一个子数组的数据,即它是一个数组,作为property的值,我想将其显示给用户。由于我是新手,所以我不知道该怎么做,我确实喜欢上了,但是却收到了这个错误

import React, { useState, useEffect } from "react";
import { Link, useParams } from "react-router-dom";
import axios from "axios";

const User = () => {
    const { id } = useParams();

    const [user, setUser] = useState({
        name: "",
        username: "",
        email: "",
        actions: []
    });

    const [action, setAction] = useState({
        actionName: "",
        actionContribution: "",
        actionDescription: ""
    });

    const loadUser = async () => {
        const res = await axios.get(`http://localhost:3003/users/${id}`);
        setUser(res.data);
        res.data.actions.map(action => {
            setAction(action);
        })
    };

    useEffect(() => {
        loadUser();
    }, []);

    return (
        <div className="container">
            <Link className="btn btn-primary" to="/">Back to Home</Link>
            <div className="row col-sm-6 offset-sm-3">
                <div className="card">
                    <div className="card-header">
                        <h1 className="card-title">Member Id:{id}</h1>
                    </div>
                    <div className="card-body">
                        <dl className="row">
                            <dt className="col-6">Name :</dt>
                            <dd className="col-6">{user.name}</dd>
                            <dt className="col-6">UserName :</dt>
                            <dd className="col-6">{user.username}</dd>
                            <dt className="col-6">Email :</dt>
                            <dd className="col-6">{user.email}</dd>
                            <dd> {action.actionName} </dd>
                            <dt className="col-6">Website</dt>
                            <dd className="col-6">{user.website}</dd>
                        </dl>
                    </div>
                </div>
                <hr />
            </div>
        </div>
    );
}
export default User;

错误是获取是

TypeError: Cannot read property 'actionName' of null

我该如何解决

2 个答案:

答案 0 :(得分:0)

状态尚不可用。因此会导致错误。

{action && <dd> { action.actionName } </dd>}

答案 1 :(得分:0)

嘿,您在使用setAction时没有检查是否定义了动作对象或您是否依赖所有属性。

我为您更新了一个建议代码,该代码在分配前使用了结构分解,并设置了默认值以帮助您指示缺少的属性。

您真的要使用地图功能来遍历所有动作条目并覆盖它们,而不是直接选择最后一个吗?

import React, { useState, useEffect } from "react";
import { Link, useParams } from "react-router-dom";
import axios from "axios";

const User = () => {
    const { id } = useParams();

    const [user, setUser] = useState({
        name: "",
        username: "",
        email: "",
        actions: []
    });

    const loadUser = async () => {
        const res = await axios.get(`http://localhost:3003/users/${id}`);

        const {
            name = "",
            username = "",
            email = "",
            actions = []
        } = res.data || {};

        const filteredActions = actions.filter((action) =>{
          return (action !== undefined && action !== null && action instanceof Object);
        });

        setUser({ name, username, email, actions: filteredActions });
    };

    useEffect(() => {
        loadUser();
    }, []);

    return (
        <div className="container">
            <Link className="btn btn-primary" to="/">Back to Home</Link>
            <div className="row col-sm-6 offset-sm-3">
                <div className="card">
                    <div className="card-header">
                        <h1 className="card-title">Member Id:{id}</h1>
                    </div>
                    <div className="card-body">
                        <dl className="row">
                            <dt className="col-6">Name :</dt>
                            <dd className="col-6">{user.name}</dd>
                            <dt className="col-6">UserName :</dt>
                            <dd className="col-6">{user.username}</dd>
                            <dt className="col-6">Email :</dt>
                            <dd className="col-6">{user.email}</dd>
                            <dd>{user.actions.map((action) => {
                                const {
                                    actionName = 'no name',
                                    actionContribution = 'no contribution',
                                    actionDescription = 'no description'
                                } = action;
                                return `${actionName} - ${actionContribution} - ${actionDescription}`;
                            })} </dd>
                            <dt className="col-6">Website</dt>
                            <dd className="col-6">{user.website}</dd>
                        </dl>
                    </div>
                </div>
                <hr />
            </div>
        </div>
    );
}

export default User;