React 列表渲染&条件渲染(3)

本文介绍了React中条件渲染的原理,强调了渲染元素必须为布尔值,并展示了LoginForm、Welcome和Tip组件的用例。此外,还探讨了列表渲染时为何不建议使用index作为key值,提出了使用nanoid生成唯一key的解决方案,以确保在列表元素增删或顺序变化时保持应用状态的清晰。
摘要由CSDN通过智能技术生成

条件渲染

判断条件一定是 bool 类型才会渲染,falsenullundefined

class LoginForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",
      pwd: "",
    };
  }
  handleUserNameChange(e) {
    this.setState({
      username: e.target.value,
    });
  }
  handlePwdChange(e) {
    this.setState({
      pwd: e.target.value,
    });
  }
  login() {
    const { username, pwd } = this.state;
    // 通过 props 将用户信息传递给 父组件
    this.props.login(username, pwd);
  }
  render() {
    return (
      <div>
        <div>
          <span>用户名:</span>
          <input type="text" onChange={(e) => this.handleUserNameChange(e)} />
        </div>
        <div>
          <span>密码:</span>
          <input type="password" onChange={this.handlePwdChange.bind(this)} />
        </div>
        <button onClick={() => this.login()}>提交</button>
      </div>
    );
  }
}

class Welcome extends React.Component {
  render() {
    return (
      <div>
        <h1>欢迎登录</h1>
        <button onClick={() => this.props.logout()}>退出登录</button>
      </div>
    );
  }
}

class Tip extends React.Component {
  render() {
    const { tipShow } = this.props;
    if (!tipShow) {
      return null;
    }
    return <p>tip</p>;
  }
}

class App extends React.Component {
  constructor() {
    super();
    this.state = { logged: false, tipShow: false };
  }
  login = (username, pwd) => {
    if (username === "123" && pwd === "123") {
      // 登录成功会重置信息
      this.setState({
        logged: true,
        tipShow: true,
      });
    }
  };
  logout = () => {
    this.setState({
      logged: false,
      tipShow: false,
    });
  };
  render() {
    const { logged, tipShow } = this.state;
    return !logged ? (
      <LoginForm login={this.login} />
    ) : (
      <div>
        <Welcome logout={this.logout} />
        <Tip tipShow={tipShow} />
      </div>
    );
  }
}

ReactDOM.render(<App />, document.querySelector("#app"));

列表渲染

报错信息:Each child in a list should have a unique "key" prop.

原因:列表中每个子元素都必需一个唯一的 key 属性值

  1. keyReact 查看元素是否改变的一个唯一标识
  2. key 必须在兄弟节点中唯一,确定的(兄弟结果是一个列表中的兄弟元素)

为什么不建议使用 index 作为 key 值?(建议在列表顺序不改变、元素不增删的情况下使用 index

列表项增删或顺序改变了,index 的对应项就会改变,key 对应的项还是之前列表对应元素的值,导致状态混乱,查找元素性能就会变差

好的做法:
如果列表是静态的,不可操作的,可以选择 index 作为 key,但也不推荐;
很有可能这个列表在以后维护扩展的时候,有可能变更为可操作的列表

  1. 尽量避免使用 index
  2. 可以用数据的 ID (也有可能变化)
  3. 使用动态生成的静态 IDnanoid
import { nanoid } from "nanoid";

class ListTitle extends React.Component {
  render() {
    return (
      <thead>
        <tr>
          <td>Key</td>
          <td>id</td>
          <td>name</td>
        </tr>
      </thead>
    );
  }
}

class ListItem extends React.Component {
  render() {
    const { sid, item } = this.props;
    return (
      <tr>
        <td>{sid}</td>
        <td>{item.id}</td>
        <td>{item.name}</td>
      </tr>
    );
  }
}

class App extends React.Component {
  state = {
    arr: [
      {
        id: 1,
        name: "zs",
      },
      {
        id: 2,
        name: "zs2",
      },
      {
        id: 3,
        name: "zs3",
      },
      {
        id: 4,
        name: "zs4",
      },
      {
        id: 5,
        name: "zs5",
      },
    ],
  };
  render() {
    return (
      <table border={1}>
        <ListTitle />
        <tbody>
          {
            // 如果多层嵌套map的话,尽量把map结果抽离出子组件,提升性能
            this.state.arr.map((item) => {
            const sid = nanoid();
            // key 不会作为属性传递给子组件,必须显示传递 key 值
            // 原因:防止开发者在逻辑中对key值进行操作
            return <ListItem key={sid} sid={sid} item={item} />;
          })}
        </tbody>
      </table>
    );
  }
}

ReactDOM.render(<App />, document.querySelector("#app"));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值