简体   繁体   English

道具不断返回未定义

[英]Prop keeps returning undefined

I'm currently trying to create a table where each row has a checkbox that can be enabled or disabled.我目前正在尝试创建一个表格,其中每一行都有一个可以启用或禁用的复选框。 I have created 3 files:我创建了 3 个文件:

  • ChangeUserGroup.jsx - This is where the data is read from a json file ChangeUserGroup.jsx - 这是从 json 文件中读取数据的位置
  • UserGroupForm.jsx - Starts the form and passes the this.prop.permissions on to the next file, which contains the table and the checkboxes. UserGroupForm.jsx - 启动表单并将this.prop.permissions传递到下一个文件,该文件包含表格和复选框。
  • TableShowPermissions.jsx - Contains the table and the problematic function + checkbox TableShowPermissions.jsx - 包含表格和有问题的 function + 复选框

I would like for the data in the ChangeUserGroup.jsx state(called groupDetails.permissions ) to control if the checkbox for the given permission is initialized with "defaultChecked".我希望 ChangeUserGroup.jsx 状态中的数据(称为groupDetails.permissions )来控制是否使用“defaultChecked”初始化给定权限的复选框。 But i am getting the following error:但我收到以下错误:

给出的错误

The files contain the following:这些文件包含以下内容:

ChangeUserGroup.jsx更改用户组.jsx

import React, { Component } from 'react';
import { Helmet } from 'react-helmet';

import { Container, Row, Col, Card, CardHeader, CardBody, Table, Button } from 'reactstrap';

import jsonData from '_testdata/userGroups';
import LoadingIcon from '_components/LoadingIcon';
import UserGroupForm from '_components/UserGroupForm';

class ChangeUserGroup extends Component {

    constructor(props) {
        super(props);

        this.state = {
            isLoading: false,
            userGroupId: 0,
            groupDetails: []
        }

    }

    componentDidMount() {
        this.setState({ isLoading: true });

        const { userGroupId } = this.props.match.params

        this.setState({
            userGroupId: userGroupId
        });

        jsonData.userGroups.filter((a) => a.id.toString() === userGroupId).map((b) => this.setState({
            groupDetails: b,
            isLoading: false
        }));
    }

    render() {

        const { groupDetails, isLoading } = this.state;

        if (isLoading) {
            return <LoadingIcon />;
        }

        return (
            <>
                <Helmet>
                    <title>{global.siteName + " - Brugergrupper"}</title>
                </Helmet>

                <main>
                    <section className="section section-shaped section-lg">

                        <Container>
                            <Row className="justify-content-center">
                                <Col lg="12">
                                    <Card className="bg-secondary shadow border-0">
                                        <CardHeader className="bg-white">
                                            <h1 className="text-center">{groupDetails.name}</h1>

                                        </CardHeader>
                                        <CardBody className="px-lg-5 py-lg-5">

                                            <UserGroupForm 
                                                id={groupDetails.id} 
                                                groupName={groupDetails.name} 
                                                position={groupDetails.position}
                                                permissions={groupDetails.permissions} />

                                        </CardBody>

                                    </Card>
                                </Col>
                            </Row>
                        </Container>
                    </section>
                </main>
            </>
        );
    }
}

export { ChangeUserGroup };

UserGroupForm.jsx用户组表单.jsx

import React, { Component } from 'react';

import { Form } from "reactstrap";

import CustomFormInput from '_components/FormStuff/CustomFormInput';
import TableShowPermissions from '_components/UserGroups/TableShowPermissions';

class UserGroupForm extends Component {

    render() {

        const { id, groupName, position, permissions } = this.props;


        return (
            <Form>
                <CustomFormInput pLabel="Gruppe navn" pIcon="fa-user" pType="text" pShowLabel="on" pValue={groupName} />
                <CustomFormInput pLabel="Gruppe position" pIcon="fa-user" pType="text" pShowLabel="on" pValue={position} />
                <hr />
                <TableShowPermissions 
                    thePermissions={permissions} />
            </Form>

        );
    }
}

export default UserGroupForm;

TableShowPermissions.jsx TableShowPermissions.jsx

import React, { Component } from 'react';

import jsonData from 'UserPermissions';

import { Table, Button } from "reactstrap";

class TableShowPermissions extends Component {

    constructor(props) {
        super(props);

        this.checkIfPermissionAdded = this.checkIfPermissionAdded.bind(this);
    }

    checkIfPermissionAdded(checkPerm) {
        const { thePermissions } = this.props;

        thePermissions.split('|').map(permC => {
            //console.log(checkPerm + " -- " + permC)
            if (checkPerm === permC) {
                return true;
            }
        });
        return false;
    }

    render() {

        return (

            <Table className="align-items-center table-bordered" responsive>
                <thead className="thead-light">
                    <tr>
                        <th scope="col">Permission navn</th>
                        <th scope="col">Beskrivelse</th>
                        <th scope="col" />
                    </tr>
                </thead>
                <tbody>

                    {jsonData.permissions.map(perm => (
                        <tr key={perm.id}>
                            <th scope="row">
                                {perm.permission}
                            </th>

                            <td>
                                {perm.description}
                            </td>

                            <td className="text-right">
                                <label className="custom-toggle">
                                    <input type="checkbox" defaultChecked={this.checkIfPermissionAdded(perm.permission)} />
                                    <span className="custom-toggle-slider rounded-circle" />
                                </label>
                            </td>
                        </tr>
                    ))}

                </tbody>
            </Table>

        );
    }
}

export default TableShowPermissions;

JSON DATA JSON 数据

{
    "userGroups": [
        {
            "id": 1,
            "name": "Administrator",
            "position": "Admin",
            "permissions": "ADMIN_ROOT|"
        },
        {
            "id": 2,
            "name": "Moderator",
            "position": "Mod",
            "permissions": "ADMIN_SETTINGS_GENERAL|ADMIN_CASES_SEEALL|ADMIN_SETTINGS_CATEGORIES"
        },
        {
            "id": 3,
            "name": "Supporters",
            "position": "Supporter",
            "permissions": "ADMIN_CASES_SEEALL|"
        }
    ]
}

Any help would be appreciated: :)任何帮助,将不胜感激: :)

If after a few react renders you do have the value, it most likely means it just isn't there yet in the first renders (this can happen if you are getting the data from a request) .如果在几次 react 渲染之后你确实有这个值,那很可能意味着它在第一次渲染中还不存在(如果你从请求中获取数据,就会发生这种情况)

You can either add an if condition to only run the split when thePermissions exist or add a default value to it.您可以添加if条件以仅在thePermissions存在时运行拆分,也可以为其添加默认值。

    checkIfPermissionAdded(checkPerm) {
        const { thePermissions } = this.props;

        if (thePermissions) {
          thePermissions.split('|').map(permC => {
              //console.log(checkPerm + " -- " + permC)
              if (checkPerm === permC) {
                return true;
              }
          });
        }

        return false;
    }

or或者

    checkIfPermissionAdded(checkPerm) {
        const { thePermissions = '' } = this.props;

        thePermissions.split('|').map(permC => {
            //console.log(checkPerm + " -- " + permC)
            if (checkPerm === permC) {
                return true;
            }
        });
        return false;
    }

It is possible that none is what you desire in your code but it might help you out knowing why it is happening.您的代码中可能没有您想要的,但它可能会帮助您了解它发生的原因。

Initialize your Loading initial state as true.将您的加载初始 state 初始化为 true。 Set your state in the constructor like this:在构造函数中设置您的 state,如下所示:

constructor(props) {
    super(props);

    this.state = {
        isLoading: true,
        userGroupId: props.match.params,
        groupDetails: []
    }
}

Remove the first two setState from your componentDidMount.从您的 componentDidMount 中删除前两个 setState。 Each time a setState is called the render fucntion is called.每次调用 setState 时都会调用渲染函数。

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

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