How to fetching data from react.js before render compontents and Cannot read property 'includes' of undefined?

烂漫一生 提交于 2020-03-25 18:14:49

问题


I have got two components, child components and parent components.

Here is data format is coming from database :

 {permissible_objects :["group", "topGroup"],all_permissions: ["can_view","can_create"]}

I am going to pass data from parent component to child components . when I pass data parent to child compontent I got an error that is

 TypeError: Cannot read property 'includes' of undefined

However, I saw data in the console.log(). Where is the problem of typeError can not undefined ? If I worked with static data, There is no problem . Everyting is worked perfectly .

  • app.js(parent compontent)

        <UserPermission
          userPermissionList={this.state.userPermissionList}
        />
    

This is my child components (UserPermission.js)

     state = {
      permission: {}

    };
  UNSAFE_componentWillMount() {
    this.setState({
      userPermissionList: this.props.userPermissionList,
      groupItems:
        this.props.userPermissionList &&
        this.props.userPermissionList.all_permissions &&
        this.props.userPermissionList.all_permissions.map(item => item.value)
    });
    this.setDefault(false);
  }

  setDefault = fill => {
    const temp = {};
    this.state.userPermissionList &&
      this.state.userPermissionList.permissible_objects &&
      this.state.userPermissionList.permissible_objects.forEach(
        x => (temp[x] = fill ? this.state.groupItems : [])
      );
    this.setState({ permission: temp });
  };
  checkLength = () => {
    const { permission } = this.state;
    let sum = 0;
    Object.keys(permission).forEach(x => (sum += permission[x].length));
    return sum;
  };

  isTotalIndeterminate = () => {
    const len = this.checkLength();
    return len > 0 && len < this.state.groupItems.length * group.length;
  };
  onCheckTotalChange = () => e => {
    this.setDefault(e.target.checked);
  };
  isTotalChecked = () => {
    return this.checkLength() === this.state.groupItems.length * group.length;
  };

these method is work for each group such as here is my two roles - one is group and another is topGroup.

  isIndeterminate = label => {
    const { permission } = this.state;
    // undefined !== theHref && theHref.length
    return permission[label] && permission[label].length !== undefined
      ? permission[label].length > 0 &&
          permission[label].length < this.state.groupItems.length
      : null;
  };
  onCheckAllChange = label => e => {
    const { permission } = this.state;
    const list = e.target.checked ? this.state.groupItems : [];
    this.setState({ permission: { ...permission, [label]: list } });
  };
  isAllChecked = label => {
    const { permission } = this.state;
    console.log(label);
    return !this.state.groupItems.some(x => !permission[label].includes(x));
  };

/** * these method is work for single item such as can_view,can_delete,can_update */

  isChecked = label => {
    const { permission } = this.state;
    return permission[label];
  };

  onChange = label => e => {
    const { permission } = this.state;
    this.setState({ permission: { ...permission, [label]: e } });
  };

Here is three checkbox

Rendering UI :

this is going to selected All checkbox .

          <Checkbox
            indeterminate={this.isTotalIndeterminate()}
            onChange={this.onCheckTotalChange()}
            checked={this.isTotalChecked()}
          >
            All
          </Checkbox>

this is worked for group based checkbox

          {permissible_objects &&
            permissible_objects.slice(0, 3).map((label, index) => (

                    <label>{label}</label>

                      <Checkbox
                        indeterminate={this.isIndeterminate(label)}
                        onChange={this.onCheckAllChange(label)}
                        checked={this.isAllChecked(label)}
                      >
                        {label}
                      </Checkbox>

this is worked for singe checkbox

                    <CheckboxGroup
                      options={this.state.groupItems}
                      value={this.isChecked(label)}
                      onChange={this.onChange(label)}
                    />

            ))}

How can I resolve Cannot read property 'includes' of undefined ?


回答1:


How can I resolve Cannot read property 'includes' of undefined ?

permission[label] needs to be defined in isAllChecked function, but initial state.permissions looks like it is empty object.

state = {
  permission: {}, // permission has no properties!!
};

...

isAllChecked = label => {
  const { permission } = this.state;
  console.log(label);
  return !this.state.groupItems.some(
    // check that permission[label] exists then check if it doesn't include `x`
    x => permission[label] && !permission[label].includes(x)
  );
};


来源:https://stackoverflow.com/questions/60779821/how-to-fetching-data-from-react-js-before-render-compontents-and-cannot-read-pro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!