简体   繁体   中英

JSX array.map undefined boolean data

i tried to display & map my objects in a table row, but my boolean datas will return as undefined and i can't even convert them into strings, whats the solution?

Look at user.isenable and user.isonline in mapping ...

this is what i tried ...

import { component, Fragment } from 'react'

class Users extends Component {
  constructor(props) {
    super(props);

    this.state = {
      users: []
    };
  }
  componentDidMount() {
    const url = "http://localhost:4000/api/user";
    // AXIOS REQUEST
    axios.get(url).then(res => {
      this.setState({ users: res.data });
      console.log(this.state.users);
    });
  }

  render() {
    const users = this.state;
    console.log(this.state.users.isenbale);
    return (
      <table id="users">
        <tr>
          <th>is Enable</th>
          <th>is Online</th>
        </tr>

        {this.state.users.map(user => {
          return (
            <tr key={user.nationalcode}>
              <td>{user.isEnable.toString()}</td>
              <td>{user.isOnline.toString()}</td>
            </tr>
          );
        })}
      </table>
    );
  }
}

console logs of res.data & this.state.users are the same.

(5) [{…}, {…}, {…}, {…}, {…}]
0: {nationalcode: 134556778, stockcode: "md3456", firstname: "ali", lastname: "khodabakhashi", isenable: true, …}
1: {nationalcode: 1334853905, stockcode: "md4f5789", firstname: "saeed", lastname: "mohammad", isenable: true, …}
2: {nationalcode: 11313, stockcode: "31313", firstname: "1313", lastname: "1313", isenable: null, …}
3: {nationalcode: 4151515, stockcode: "151", firstname: "5131", lastname: "3114", isenable: null, …}
4: {nationalcode: 123456789, stockcode: "3131", firstname: "31", lastname: "3131", isenable: null, …}
length: 5
__proto__: Array(0)

There is two issues.

  1. In the example users object you provided it is isenable with lowercase. However, you are trying to reference isEnable
  2. Some of your isenable fields are null . This does not have a toString method

As null is falsy, you can short circuit it.

Here is an example

In the data, you're receiving isenable is all lowercase but in the code, you're using it as isEnable , javascript variable names are case sensitive so the engine treat them as two different things.

Change the code to user.isenable and it should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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